Given initially empty stacks, there are three types of operations:
1 s v: Push the value onto the top of the -th stack.
2 s: Pop the topmost value out of the -th stack, and print that value. If the -th stack is empty, pop nothing and print "EMPTY" (without quotes) instead.
3 s t: Move every element in the -th stack onto the top of the -th stack in order.
Precisely speaking, denote the original size of the -th stack by , and the original size of the -th stack by . Denote the original elements in the -th stack from bottom to top by , and the original elements in the -th stack from bottom to top by .
After this operation, the -th stack is emptied, and the elements in the -th stack from bottom to top becomes . Of course, if , this operation actually does nothing.
There are operations in total. Please finish these operations in the input order and print the answer for every operation of the second type.
Input
There are multiple test cases. The first line of the input contains an integer , indicating the number of test cases. For each test case:
The first line contains two integers and (), indicating the number of stacks and the number of operations.
The first integer of the following lines will be (), indicating the type of operation.
- If , two integers and (, ) follow, indicating an operation of the first type.
- If , one integer () follows, indicating an operation of the second type.
- If , two integers and (, ) follow, indicating an operation of the third type.
It's guaranteed that neither the sum of nor the sum of over all test cases will exceed .
Output
For each operation of the second type output one line, indicating the answer.
Sample Input
2 2 15 1 1 10 1 1 11 1 2 12 1 2 13 3 1 2 1 2 14 2 1 2 1 2 1 2 1 2 1 3 2 1 2 2 2 2 2 2 3 7 3 1 2 3 1 3 3 2 1 2 1 2 2 2 3 2 3
Sample Output
13 12 11 10 EMPTY 14 EMPTY EMPTY EMPTY EMPTY EMPTY EMPTY
题意:n个栈 q次操作 ,op=1 向s栈压入v,op=2 弹出s栈的栈顶,op=3 将v栈接在s栈后。
思路:纯纯的模拟题目,但是由于没有涉及过list所以没有AC,但是使用stack的话是先是爆内存,然后再爆时间,STL在每次 变长内存空间的时候是2倍的指数增长的,所以就是他的一个测试的样例就是刚好会使stl两倍的增长。时间爆是stack每次替换元素会o(n)。list是一个线性双向链表结构,它的数据由若干个节点构成,每一个节点都包括一个信息块(即实际存储的数据)、一个前驱指针和一个后驱指针。它无需分配指定的内存大小且可以任意伸缩,这是因为它存储在非连续的内存空间中,并且由指针将有序的元素链接起来。
C++中list用法详解 https://blog.csdn.net/yas12345678/article/details/52601578
#include <bits/stdc++.h>
#include <list>
using namespace std;
const int maxn = 3e5+5;
list<int> l[maxn];
int main()
{
int n,t,q;
scanf("%d",&t);
while(t--){
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
l[i].clear();
while(q--){
int op,s,v,t;
scanf("%d",&op);
if(op==1){
scanf("%d%d",&s,&v);
l[s].push_back(v);
}
else if(op==2){
scanf("%d",&s);
if(l[s].empty()) printf("EMPTY\n");
else{
printf("%d\n",l[s].back());
l[s].pop_back();
}
}
else if(op==3){
scanf("%d%d",&s,&t);
l[s].splice(l[s].end(),l[t]); //splice 直接进行合并不进行排序,merge默认升序合并排序
}
}
}
return 0;
}