#include<bits/stdc++.h>
using namespace std;
typedef set<int> Set;
map<Set,int> IDcache;
vector<Set> Setcache;
stack<int> s;
int ID(Set x)
{
if(IDcache.count(x)) return IDcache[x];
Setcache.push_back(x);
return IDcache[x]=Setcache.size()-1;
}
int t,n;
int main()
{
int i,j;
string op;
Set x1,x2,x;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%d",&n);
for(j=1;j<=n;j++)
{
cin>>op;
if(op[0]=='P')
s.push(ID(Set()));
else if(op[0]=='D')
s.push(s.top());
else
{
x1.clear();x2.clear();x.clear();
x1=Setcache[s.top()];s.pop();
x2=Setcache[s.top()];s.pop();
//http://blog.youkuaiyun.com/zangker/article/details/22984803
//http://blog.youkuaiyun.com/neo_2011/article/details/7366248
//最后一个参数若使用x.begin()会产生编译错误assignment of read-only localtion.
//但是如果x是vector则可以直接用x.begin()
if(op[0]=='U')
set_union(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
if(op[0]=='I')
set_intersection(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
if(op[0]=='A')
{
x=x2;
x.insert(ID(x1));
}
s.push(ID(x));
}
printf("%d\n",Setcache[s.top()].size());
}
printf("***\n");
}
return 0;
}
set_union的说明
合并集合(set<...>)x1,x2,并放入新集合x
set_union(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
合并数组x1,x2(要求原本有序):
#include<bits/stdc++.h>
using namespace std;
int main()
{
int first[]={1,2,3,4,5};
int second[]={3,4,5,6,7};
int third[10]={0};
set_union(first,first+5,second,second+5,third);
//set_union(begin(first),end(first),begin(second),end(second),begin(third));//作用同上,begin()和end()是c++11新特性
for(int i=0;i<10;i++)
printf("%d ",third[i]);
}
#include<bits/stdc++.h>//没排序就像这样,输出奇怪的东西
using namespace std;
int main()
{
int first[]={1,2,3,4,5};
int second[]={7,4,6,5,4};
int third[10]={0};
set_union(first,first+5,second,second+5,third);
for(int i=0;i<10;i++)
printf("%d ",third[i]);
}
求集合x1,x2的交集,并放入新集合x
set_intersection(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
(数组类似)