本题的集合并不是简单的整数集合或者字符串集合,而是集合的集合(一个比较抽象的问题)。为了方便起见,此处为每个不同的集合分配一个唯一的ID,则可以将集合的集合转化为int类型的集合。整个栈是一个stack<int>。
有多组数据的时候要初始化栈!
#include<iostream>
#include<cstdio>
#include<stack>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#define ALL(x) x.begin(),x.end() //所有的内容
#define INS(x) inserter(x,x.begin()) //插入迭代器
using namespace std;
typedef set<int> Set; //后面较方便
map<Set,int> IDcache; //在查找元素ID的时候有用
vector<Set> Setcache; //根据集合取ID,因为ID是数,所以直接用数组
stack<int> s;
int n,m;
int ID (Set x) {
if (IDcache.count(x)) return IDcache[x];
Setcache.push_back(x);
return IDcache[x] = Setcache.size() - 1; //与上一个语句相对应
}
int main()
{
cin>>n;
while (n-- && cin >> m) {
while (m--) {
string op;
cin>>op;
if (op[0] == 'P') s.push(ID(Set ())); //每次只取第一个字母判断,减少程序时间
else if (op[0] == 'D') s.push(s.top());
else {
Set s1 = Setcache[s.top()]; s.pop();
Set s2 = Setcache[s.top()]; s.pop();
Set x;
if (op[0] == 'U') set_union (ALL(s1), ALL(s2), INS(x));
if (op[0] == 'I') set_intersection (ALL(s1), ALL(s2), INS(x));
if (op[0] == 'A') {
x = s2; x.insert(ID(s1)); //Set是int类型的集合,里面存储的是各个集合的ID编号
}
s.push(ID(x));
}
cout<< Setcache[s.top()].size() << endl;
}
cout<<"***"<<endl;
}
return 0;
}