12096 The SetStack Computer
Background from Wikipedia: Set theory is a branch ofmathematics created principally by the German mathe-matician Georg Cantor at the end of the 19th century.
Initially controversial, set theory has come to play therole of a foundational theory in modern mathematics,and ADD.
PUSH will push the empty set fg on the stack.
DUP will duplicate the topmost set (pop the stack, and then push that set on the stack twice).
UNION will pop the stack twice and then push the union of the two sets on the stack.
INTERSECT will pop the stack twice and then push the intersection of the two sets on the stack.
ADD will pop the stack twice, add the rst set to the second one, and then push the resulting seton the stack.
Input
An integer 0 <= T<= 5 on the rst line gives the cardinality of the set of test cases. The rst line of each
test case contains the number of operations 0 <=N <= 2000. Then follow N lines each containing one of
the ve commands. It is guaranteed that the SetStack computer can execute all the commands in the
sequence without ever popping an empty stack.
Output
For each operation speci ed in the input, there will be one line of output consisting of a single integer.
This integer is the cardinality of the topmost element of the stack after the corresponding command
has executed. After each test case there will be a line with `***‘ (three asterisks).
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
2
2
***
0
0
1
0
0
***
维护
PUSH: 在栈顶加入一个空集合
DUP: 把栈顶集合
UNION: 弹出栈顶集合
INTERSECT: 弹出栈顶集合
ADD: 弹出栈顶集合
对于每个操作, 输出栈顶集合
用set来模拟集合,对不同的集合进行序号化,然后把序号化的数字压入栈中,取出再由序号找到对应的集合输出栈顶集合元素个数即可,需要一定的对stl运用的能力
#include<iostream> #include<stack> #include<map> #include<set> #include<string> #include<algorithm> #include<vector> using namespace std; map<set<int>,int> IDcache; //对不同集合进行序号化 vector<set<int > > Setcache; //根据序号取出集合 int ID(set<int> x) { if(IDcache.count(x)) return IDcache[x]; else { Setcache.push_back(x); return IDcache[x]=Setcache.size()-1; } } int main() { int cases,n; cin>>cases; while(cases--) { cin>>n; stack<int>s; while(!s.empty()) s.pop(); //对stack做清空初始化。 IDcache.clear(); Setcache.clear(); for(int i=0;i<n;i++) { string op; set<int> x1,x2,x; cin>>op; if(op[0]=='P') x=set<int>(); //或者写成“if(op[0]=='P');”就是让x是空的集合即可,元素是空即可。 if(op[0]=='D') { x=Setcache[s.top()]; } if(op[0]=='U'){ x1=Setcache[s.top()]; s.pop(); x2=Setcache[s.top()]; s.pop(); set_union(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin())); //取并集函数 } if(op[0]=='I'){ x1=Setcache[s.top()]; s.pop(); x2=Setcache[s.top()]; s.pop(); set_intersection(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin())); //取交集函数 } if(op[0]=='A'){ x1=Setcache[s.top()]; s.pop(); x2=Setcache[s.top()]; s.pop(); x =x2; x.insert(IDcache[x1]); } s.push(ID(x)); cout<<Setcache[s.top()].size()<<endl; } cout<<"***\n"; } return 0; }
UVAOJ 12096 The SetStack Computer(STL的运用)
原文:http://blog.csdn.net/kalilili/article/details/43412099