分析:本题的集合并不是数字或字母,而是集合的集合。我们不妨给每个集合分配唯一的ID,则每个集合都可以表示成所包含元素的ID集合,这就可以用set<int>来表示了,而整个栈则是stack<int>,注意这里所谓的ID并不是真实的数字,而是集合数组的标号。
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <stack>
#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;
vector<Set> Setcache;
stack<int> stk;
int ID(Set x)
{
if(IDcache.count(x)) return IDcache[x];
Setcache.push_back(x);
return IDcache[x] = Setcache.size() - 1;
}
int main()
{
int T,n;
cin >> T;
while(T--)
{
cin >> n;
string op;
while(n--)
{
cin >> op;
if(op[0]=='P')stk.push(ID(Set()));
else if(op[0]=='D') stk.push(stk.top());
else{
Set x1 = Setcache[stk.top()]; stk.pop();
Set x2 = Setcache[stk.top()]; stk.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));}
stk.push(ID(x));
}
cout << Setcache[stk.top()].size() << endl;
}
cout << "***" << endl;
}
return 0;
}

本文介绍了一种使用栈数据结构来实现集合操作的方法,包括并集、交集和添加等操作,并通过分配唯一ID来简化集合的管理和操作。
675

被折叠的 条评论
为什么被折叠?



