UVA

来源:互联网 发布:js去掉属性值 编辑:程序博客网 时间:2024/06/05 06:55
/*  注释十分详尽的blog:  http://blog.csdn.net/a197p/article/details/43407901    思路:  本题的集合不是简单的整数集合或字符串集合,而是集合的集合,为了方便表示,可以为每个不同的集合分配唯一的ID,则每个集合都可以表示成所包含元素的ID集合  这样就能用STL的set<int>来表示了,而整个栈就是一个stack<int>    收获:  1. Set(STL)  #define ALL(x) x.begin(), x.end()  #define INS(x) inserter(x, x.begin())  set_union(ALL(x1), ALL(x2), INS(x))表示x是x1 和 x2 的并集  set_intersection(ALL(x1), ALL(x2), INS(x)) 表示x是 x1 和 x2 的交集*/



#include <bits/stdc++.h>using namespace std;typedef set<int> Set;map<Set, int> IDcache; //把集合映射成IDvector<Set> Setcache; // 根据ID取集合, 元素为集合的不定长数组//查找给定集合的ID。如果找到了,则返回它的ID,否则,分配一个新ID并返回//对于任意类型为Set的集合s,IDcache[s]就是它的ID,而 Setcache[IDcache[s]] 就是 s本身 int ID (Set x){if (IDcache.count(x)) return IDcache[x];Setcache.push_back(x);return IDcache[x] = Setcache.size() - 1;}#define ALL(x) x.begin(), x.end()#define INS(x) inserter(x, x.begin())//这两个宏分别表示 所有的内容 和 插入迭代器,定义这两个宏以后,可以通过 STL 内置的集合操作, set_union 和 set_intersection,来实现集合的取并集和取交集int main(){stack<int>s;int k, n;cin >> k;while (k--){//while (!s.empty()) s.pop();cin >> n;for (int i = 0; i < n; i++){string op;cin >> op;if (op[0] == 'P') s.push(ID(Set())); //空集入栈,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(); // 出栈两个集合,并存放在x1和x2中Set x; //定义集合x作为中间变量if (op[0] == 'U') set_union(ALL(x1), ALL(x2), INS(x));else if (op[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x));else if (op[0] == 'A'){x = x2; x.insert(ID(x1)); //将集合x1对应的ID压栈 }s.push(ID(x)); } cout << Setcache[s.top()].size() << endl; //将栈顶的int型元素ID变为其对应的真正的集合,再求这个集合的大小}cout << "***" << endl; } return 0;}


原创粉丝点击