UVA12096 The SetStack Computer
链接:https://vjudge.net/problem/UVA-12096
STL提供3种特殊的数据结构:栈、队列与优先队列。所谓栈,就是符合“后进先出”(Last In First Out, LIFO)规则的数据结构,有PUSH和POP两种操作,其中PUSH把元素压入“栈顶”,而POP从栈顶把元素“弹出”。STL的栈定义在头文件<stack>中,可以用“stack<int> s”方式定义,用push()和pop()是实现元素的入栈和出栈操作,top()取栈顶元素(但不删除)。
本题的集合并不是简单的整数集合或者字符串集合,而是集合的集合。为了方便起见,此处为每个不同的集合分配一个唯一的ID,则每个集合都可以表示成所包含元素的ID集合,这样就可以用STL的set<int>来表示了,而整个栈则是一个stack<int>。
对任何集合s(类型时上面定义的Set),IDcache[s]就是它的ID,而Setcache[IDcache[s]]就是s本身。ALL和INS是两个宏。ALL表示“所有的内容”,INS表示“插入迭代器”。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <set> #include <map> #include <vector> #include <stack> #include <algorithm> #define ALL(x) x.begin(),x.end()//所有的内容 #define INS(x) inserter(x,x.begin())//插入迭代器 using namespace std; typede set<int> Set; map<Set,int> IDcache//把集合映射成ID vector<Set> Setcache;//根据ID取集合 //查找给定集合x的ID。如果找不到,分配一个新ID int ID (Set x) { if(IDcache.count(x)) return IDcache[x]; Setcache.push_back(x); return IDcache[x]=Setcache.size()-1; } int main() { stack<int> s;//题目中的栈 int n,t; cin>>t; while(t--) { cin>>n; for(int 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; } cout<<"***\n"; } return 0; }