The Setstack computer
Time limit:3.000 seconds
The topic is this:
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.
(Input: First enter the number of tests, then enter the number of operations, and then enter the specific operation)
Sample Input
2
9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION
5
PUSH
PUSH
ADD
PUSH
INTERSECT
Sample Output
0
0
1
0
1
1
2
***
0
0
1
0
0
***
Analysis
Assigning a unique ID to each different collection allows each collection to be represented as an ID collection of the contained elements, which can be represented by the set<int> of the STL, while the entire stack is a stack<int>.
In the C + + language program, the code is as follows:
#include <iostream> #include <string> #include <set> #include <map> #include <stack># Include<vector> #include <algorithm>using namespace Std;typedef set<int> set;//defines an int type set object Set, There is currently no element .map<set,int> idcache;//maps the collection to idvector<set> setcache;//find the ID of the collection. If not found, assign a new Idint ID (Set x) {if ( Idcache.count (x)) return idcache[x]; Setcache.push_back (x); Return Idcache[x]=setcache.size ()-1;} #define ALL (x) X.begin (), X.end () #define INS (x) Inserter (X,x.begin ()) int main () {int T; cin>>t; while (t--) {stack<int> s; int i,n; cin>>n; for (i=0; i<n; i++) {string op; 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 ()]; S.pop (); Set x2=setcache[s.top ()]; S.pop (); Set x; if (op[0]== ' U ') set_union (All (x1), All (x2), INS (x)); if (op[0]== ' I ') set_intersection (All (x1), All (x2), INS (x)); if (op[0]== ' A ') {x=x2; X.insert (ID (x1)); } s.push (ID (x)); } cout<<setcache[s.top ()].size () <<endl; }}return 0;}
Rujia is a set-to-int mapping
Introduction to the algorithm Classic-fifth chapter 5-5 collection stack computer