There is a "collection stack" computer designed specifically for set operations. The machine has a stack that is initially empty and supports the following operations:
Push: Empty set "{}" into the stack
DUP: Copy the top element of the current stack and then into the stack
UNION: Stacks up to two sets, and then sets the combination of the two into a stack
INTERSECT: Two sets of stacks, and then the intersection of the two into the stack
Add: Stack up to two sets, then add the first-out stack to the collection of the stack, and put the result into the stack
The size of the top collection of output stacks (that is, the number of elements) after each operation. For example, the top element of the stack is a={{}, {{}}}, the next element is b={{}, {{}}}, then:
The union operation will get {{}, {{}}, {{{}}}, Output 3.
Intersect operation will get {{}}, Output 1
The add operation will get {{}, {{}}}, {{}, {{}}}, Output 3.
Enter no more than 2000 operations
Sample Input
9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION
Sample Output
0
0
1
0
1
1
2
2
2
#include <iostream>#include<string>#include<algorithm>#include<iterator>#include<vector>#include<Set>#include<map>#include<stack>using namespaceStd;typedefSet<int>Set; Map<set,int> Idcache;//Map a collection to an IDVector<set>Setcache; intID (Set x)//finds the ID of the given collection x, if not found, assigns a new ID{ if(Idcache.count (x))returnIdcache[x]; Setcache.push_back (x); //Add a new collection returnIdcache[x]=setcache.size ()-1;}#defineAll (x) X.begin (), X.end ()#defineINS (x) Inserter (X,x.begin ())intMain () {stack<int>s; intN; CIN>>N; for(intI=0; i<n;i++){ stringop; CIN>>op; if(op[0]=='P') S.push (ID (Set ())); Else if(op[0]=='D') S.push (S.top ()); Else{Set x1=setcache[s.top ()];//Top () takes the topmost element of the stack (but does not delete)S.pop ();//Pop () removes the top element of the stack from the top of the stackSet x2=setcache[s.top ()]; S.pop (); //Take out the last number and the second one and deleteSet x; if(op[0]=='U') Set_union (All (x1), All (x2), INS (x));//Seek and set if(op[0]=='I') Set_intersection (All (x1), All (x2), INS (x));//ask for intersection if(op[0]=='A') {x=x2; X.insert (ID (x1)); } s.push (ID (x)); } cout<<setcache[s.top ()].size () <<Endl; } System ("Pause"); return 0;}
Stack collection stack computer (pick)