集合栈计算机(The SetStack Computer, ACM/ICPC NWERC 2006,Uva12096)

时间:2023-03-08 22:21:59

集合栈计算机(The SetStack Computer, ACM/ICPC NWERC 2006,Uva12096)

题目描述

有一个专门为了集合运算而设计的“集合栈”计算机。该机器有一个初始为空的栈,并且支持以下操作:

PUSH:空集“{}”入栈

DUP:把当前栈顶元素复制一份后再入栈

UNION:出栈两个集合,然后把两者的并集入栈

INTERSECT:出栈两个集合,然后把二者的交集入栈

ADD:出栈两个集合,然后把先出栈的集合加入到后出栈的集合中,把结果入栈

       每次操作后,输出栈顶集合的大小(即元素个数)。例如栈顶元素是A={ {}, {{}} }, 下一个元素是B={ {}, {{{}}} },则:

UNION操作将得到{ {}, {{}}, {{{}}} },输出3.

INTERSECT操作将得到{ {} },输出1

ADD操作将得到{ {}, {{{}}}, { {}, {{}} } },输出3.

样例输入

6

PUSH

PUSH

UNION

PUSH

PUSH

ADD

样例输出

0

0

0

0

0

1

代码实现

#define LOCAL
#include<set>
#include<stack>
#include<iostream>
#include<map>
#include<vector>
#include<algorithm> // for set_union set_intersection
using namespace std; /*
push:空集{}入栈
union:出栈两个集合,然后把两者的并集入栈
intersect:出栈两个集合,然后把二者的交集入栈
add:出栈两个集合,然后把先出栈的集合加入到后出栈的集合中,把结果入栈。
*/
typedef set<int> Set;
map<Set,int> IDcache; //set - id such as:IDcache[set]
vector<Set> SetCache; //id - cache such as:SetCache[id]
stack<int> s;
int ID(Set x){ //光一个map数据结构还不够,这是因为有可能一个Set还没有对应的id,所以这个函数应该包括的功能有:1.创建id(如果没有) 2.返回id
if(!IDcache.count(x)){
SetCache.push_back(x);
IDcache[x]=SetCache.size()-1;//!!!骚操作
}
return IDcache[x];
}
int n;
int main(){
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif cin>>n;
while(n--){
string exec;
cin>>exec;
if(exec[0] == 'P') s.push(ID(Set()));
else if(exec[0] == 'D') s.push(s.top());
else{
Set x1 = SetCache[s.top()];
s.pop();
Set x2 = SetCache[s.top()];
s.pop();
Set x;
if(exec[0] == 'U') set_union(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));//!!!inserter
if(exec[0] == 'I') set_intersection(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));//!!!inserter
if(exec[0] == 'A'){
x=x2;
x.insert(ID(x1));
}
s.push(ID(x));
}
cout<<SetCache[s.top()].size()<<endl;
}
}