原题链接:https://vjudge.net/problem/UVA-12096
分类:<stack>
备注:stack与STL其他容器的综合运用
前言:第一次看这些真是一脸懵逼,set还有这种操作?STL综合运用这么神奇?因为这个题我才了解到空集作为元素原来是这样的…对,代码几乎就是从作者那里搬来的,不用怀疑。
set_union是取并集的函数,set_intersection的取交集的函数,此外还有取差集,对称差集(环和)的函数,这些函数的参数都是一样的。头文件是<algorithm>。
inserter函数:插入迭代器。头文件是<iterator>。需要把集合A,B运算后得到的结果插入集合C时(相当于集合C就是运算结果),使用该函数。
思路
- 建立元素为set<int>的vector,对于每个新出现的集合,如果vector中没有该集合,则用map映射给该集合一个编号,并且将该集合存入vector中,这个编号即是该集合在vector中所在位置的下标。
- 建立stack<int>,其中存放的是集合的编号,不同集合的编号是没有重复的,每种集合也只有一个编号。
- 利用取交集和取并集的函数进行操作。
- 理解好set<int>中的元素含义,set<int>中的元素是用编号来代替的集合(和上面的stack一样),set<int>是集合族,元素个数即是集合个数。
- 利用vector找到栈顶(栈顶即下标)对应的set<int>,set自带取元素个数的操作,set.size()。
代码如下:
#include<cstdio>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<algorithm>
#include<iterator>
using namespace std;
int T, N;
set<int>Set;
map<set<int>, int>xb;
vector<set<int> >Set_store;
int ID(set<int> x)
{
if (xb.count(x))return xb[x];
Set_store.push_back(x);
return xb[x] = Set_store.size() - 1;
}
int main(void)
{
scanf("%d", &T);
while (T--)
{
stack<int>st;
scanf("%d", &N); getchar();
while (N--)
{
char cmd[10]; scanf("%s", cmd);
if (cmd[0] == 'P')st.push(ID(set<int>()));//建立空集的操作
else if (cmd[0] == 'D')st.push(st.top());
else
{
set<int>x1 = Set_store[st.top()]; st.pop();
set<int>x2 = Set_store[st.top()]; st.pop();
set<int>x;
if (cmd[0] == 'U')set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));//取并集
if (cmd[0] == 'I')set_intersection(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));//取交集
if (cmd[0] == 'A')x = x2, x.insert(ID(x1));
st.push(ID(x));
}
printf("%d\n", Set_store[st.top()].size());
}
printf("***\n");
}
return 0;
}