Joint Stacks
Time Limit: 8000/4000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 828 Accepted Submission(s): 403
A mergeable stack is a stack with "merge" operation. There are three kinds of operation as follows:
- push A x: insert x into stack A
- pop A: remove the top element of stack A
- merge A B: merge stack A and B
After an operation "merge A B", stack A will obtain all elements that A and B contained before, and B will become empty. The elements in the new stack are rearranged according to the time when they were pushed, just like repeating their "push" operations in one stack. See the sample input/output for further explanation.
Given two mergeable stacks A and B, implement operations mentioned above.
9
9
#include <cstdio>
#include <algorithm>
using namespace std; const int MAXN = 1e5+5;
int x[MAXN]; //记录数值
int s[3][MAXN]; //三个栈(s[0][]代表A, s[1][]代表B, s[2]代表C)记录时间戳,即x[]的下标
int top[3]; //三个栈的栈顶
int n; void solve()
{
char op[10], obj[5];
top[0] = top[1] = top[2] = 0;
for(int i = 0; i < n; ++i){
scanf("%s%s", op, obj);
int oo = obj[0]-'A';
if(op[1] == 'u'){
scanf("%d", &x[i]);
s[oo][top[oo]++] = i; //记录时间戳i,对应栈顶++
}
else if(op[1] == 'o'){
if(top[oo] == 0) //要pop的栈为空时,改为对C栈进行操作
oo = 2;
printf("%d\n", x[s[oo][--top[oo]]]);
}
else{
scanf("%s", obj);
//合并栈A和栈B放到栈C(合并的是时间戳)
top[2] = merge(s[0], s[0]+top[0],
s[1], s[1]+top[1],
s[2]+top[2]) - s[2];
top[0] = top[1] = 0;
}
}
} int main()
{
int cn = 0;
while(scanf("%d", &n), n){
printf("Case #%d:\n", ++cn);
solve();
}
return 0;
}