UVA12096 The Set Stack Computer 解题报告
题目链接
https://vjudge.net/problem/UVA-12096
题目大意
有一个专门为了集合运算而设计的“集合栈”计算机。该机器有一个初始为空的栈,并且支持以下操作。
PUSH:空集“{}”入栈。
DUP:把当前栈顶元素复制一份后再入栈。
UNION:出栈两个集合,然后把二者的并集入栈。
INTERSECT:出栈两个集合,然后把二者的交集入栈。
ADD:出栈两个集合,然后把先出栈的集合加入到后出栈的集合中,把结果入栈。
每次操作后,输出栈顶集合的大小(即元素个数)
输入不超过2000个操作,并且保证操作均能顺利进行(不需要对空栈执行出栈操作)。
解题思路
为了方便起见,我们将每个不同的集合分配一个唯一的整数ID,则每个集合都可以表示成所包含元素的ID集合。剩下的就是根据题意模拟即可,集合的并集交集需要用到set的set_union()方法和set_intersection()方法。具体实现细节请见代码和注释。
代码
#include <bits/stdc++.h>
using namespace std;
typedef set<int> Set;
map<Set, int> IDcache; // 把集合映射成ID
vector<Set> Setcache; // 根据ID取集合
#define ALL(x) x.begin(),x.end() // 所有的内容
#define INS(x) inserter(x,x.begin()) // 插入迭代器
// 查找给定集合x的ID。如果找不到,则分配一个新的ID
int ID(Set x)
{
// 如果之前有这个集合,有过记录的话,则直接返回它的ID
if(IDcache.count(x))
{
return IDcache[x];
}
// 如果没有记录过,代表这是一个新的集合,那么我们添加新集合
Setcache.push_back(x);
// 返回新集合的ID
return IDcache[x] = Setcache.size() - 1;
}
int main()
{
int t;
cin >> t;
while(t--)
{
stack<int> s; // 题目中的栈
int n;
cin >> n;
while(n--)
{
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()];
s.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;
}
cout << "***" << endl;
}
return 0;
}