標籤:
有一個專門為了集合運算而設計的“集合棧”電腦。該機器有一個初始為空白的棧,並且支援以下操作:
PUSH:空集“{}”入棧
DUP:把當前棧頂元素複製一份後再入棧
UNION:出棧兩個集合,然後把兩者的並集入棧
INTERSECT:出棧兩個集合,然後把二者的交集入棧
ADD:出棧兩個集合,然後把先出棧的集合加入到後出棧的集合中,把結果入棧
每次操作後,輸出棧頂集合的大小(即元素個數)。例如棧頂元素是A={ {}, {{}} }, 下一個元素是B={ {}, {{{}}} },則:
UNION操作將得到{ {}, {{}}, {{{}}} },輸出3.
INTERSECT操作將得到{ {} },輸出1
ADD操作將得到{ {}, {{{}}}, { {}, {{}} } },輸出3.
輸入不超過2000個操作
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 namespace std;typedef set<int> Set; map<Set,int> IDcache; //把集合映射成IDvector<Set> Setcache; int ID(Set x) //尋找給定集合x的ID,如果找不到,分配一個新ID{ 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() { stack<int> s; int n; 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()]; //top()取棧頂元素(但不刪除) s.pop(); //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; } system("pause"); return 0;}
stack 集合棧電腦 (摘)