集合栈计算机(UVa12096)

 

  题目具体描述见:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3248

 

算法流程如下:

 

C++11代码如下:

 1 #include<iostream>
 2 #include<vector>
 3 #include<string>
 4 #include<map>
 5 #include<set>
 6 #include<stack>
 7 #include<algorithm>
 8 #include<iterator>
 9 using namespace std;
10 
11 typedef set<int> Set;
12 map<Set, int>IDcache;
13 vector<Set>Setcache;
14 
15 // #define ALL(x) x.begin(),x.end()
16 // #define INS(x) inserter(x,x,begin())
17 
18 int ID(Set x) {
19     if (IDcache.count(x)) return IDcache[x];  //map中已有key(x),返回对应的value值
20     Setcache.push_back(x);   //map中没有key(x),将其插入vector 中
21     return IDcache[x] = Setcache.size() - 1;   //将key(x)存入map中,并将对应的value赋值为在vector中的下标
22 }
23 
24 int main() {
25     int n, k;
26     stack<int>s;
27     cin >> n;
28     while (n--) {
29         cin >> k;
30         while (k--) {
31             string str;
32             cin >> str;
33             if (str[0] == 'P') s.push(ID(Set()));   //空集入栈
34             else if (str[0] == 'D') s.push(s.top());
35             else {
36                 Set x1 = Setcache[s.top()]; s.pop();
37                 Set x2 = Setcache[s.top()]; s.pop();
38                 Set x;
39                 if (str[0] == 'U') set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));
40                 if (str[0] == 'I') set_intersection(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));
41                 if (str[0] == 'A') { x = x2; x.insert(ID(x1)); }  //将x1的ID插入到x中
42                 s.push(ID(x));  //合并后的x存入vector中,再将ID压入栈中
43             }
44             cout << Setcache[s.top()].size() << endl;        
45         }
46         cout << "***" << endl;
47     }
48     return 0;
49 }
posted on 2018-07-06 18:13  Pink.Pig  阅读(695)  评论(2编辑  收藏  举报