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.
4 push A 1 push A 2 pop A pop A 9 push A 0 push A 1 push B 3 pop A push A 2 merge A B pop A pop A pop A 9 push A 0 push A 1 push B 3 pop A push A 2 merge B A pop B pop B pop B 0
Case #1: 2 1 Case #2: 1 2 3 0 Case #3: 1 2 3 0
读完题意 可以知道 这道题 跟栈有关系,可以知道题上涉及两个栈,但是我们可以定义四个栈,a,b,可以在没有出现merge的时候,存下a,b里面的数据 而且方便出栈,另外,再有两个栈,d是负责中间(相当于中间变量),方便给c栈,这样可以出来的时候符合题意。
另外注意:栈是一头进一头出(同一头)。
#include<algorithm>
#include<iostream>
#include<math.h>
#include<string.h>
#include<stack>
using namespace std;
struct node
{
int id;
int shu;
};
int main()
{
int n,t1=1;
while(~scanf("%d",&n)&&n)
{
stack<node>a;
stack<node>b;
stack<node>c;
stack<node>d;
node num;
char str[10],s[10],s1[10];
int t=0,i;
printf("Case #%d:\n",t1++);
while(n--)
{
scanf("%s",str);
if(strcmp(str,"push")==0)
{
scanf("%s%d",s,&num.shu);
if(s[0]=='A')
{
num.id=t;
a.push(num);
t++;
}
else
{
num.id=t;
b.push(num);
t++;
}
}
else if(strcmp(str,"pop")==0)
{
scanf("%s",s);
if(s[0]=='A')
{
if(!a.empty())
{
printf("%d\n",a.top().shu);
a.pop();
}
else
{
printf("%d\n",c.top().shu);
c.pop();
}
}
if(s[0]=='B')
{
if(!b.empty())
{
printf("%d\n",b.top().shu);
b.pop();
}
else
{
printf("%d\n",c.top().shu);
c.pop();
}
}
}
else if(strcmp(str,"merge")==0)
{
scanf("%s%s",s,s1);
while(!a.empty()&&(!b.empty()))
{
node numa=a.top(),numb=b.top();
if(numa.id>numb.id)
{
d.push(numa);
a.pop();
}
else
{
d.push(numb);
b.pop();
}
}
while(!a.empty())
{
d.push(a.top());
a.pop();
}
while(!b.empty())
{
d.push(b.top());
b.pop();
}
while(!d.empty())
{
c.push(d.top());
d.pop();
}
}
}
}
return 0;
}