题意:有n个栈,有q个操作,操作有3种。
1 s t:在第s个栈中push元素t
2 s :弹出第s个栈的栈顶,并输出这个数
3 s t:将第t个栈直接加到第s个栈顶之后,第t个栈清空。第s个栈栈顶加入从第t个栈栈底到栈顶所有元素,也就是合并栈
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<list>
using namespace std;
const int maxn=3e5+10;
typedef long long ll;
list<int> l[maxn];
int main(){
int T, n, q;
scanf("%d", &T);
while(T--){
scanf("%d%d", &n, &q);
for(int i=1; i<=n; i++)
l[i].clear();
int op;
while(q--){
scanf("%d", &op);
if(op==1)
{
int s, v;
scanf("%d%d", &s, &v);
l[s].push_back(v);
}
else if(op==2)
{
int s;
scanf("%d", &s);
if(l[s].empty())
printf("EMPTY\n");
else
{
printf("%d\n", l[s].back());
l[s].pop_back();
}
}
else
{
int s, t;
scanf("%d%d", &s, &t);
l[s].splice(l[s].end(), l[t]);
}
}
}
return 0;
}