uva 12096 The SetStack Computer(STL set的各种库函数 交集 并集 插入迭代器)

题意:

有5种操作:

PUSH:加入“{}”空集合入栈。

DUP:栈顶元素再入栈。

UNION:出栈两个集合,取并集入栈。

INTERSECT:出栈两个集合,取交集入栈。

ADD:出栈两个集合,将先出栈的加入到后出栈的集合中。

输入不超过2000, 保证操作顺利进行。

分析:

用set<int>(本身又可以映射成一个int)去模拟集合,所以可以将不同的集合映射成int型。

用一个Map<set<int>,int> 去映射成不同的int。

以后需要set做交集并集的时候再从map中拿出set做操作再映射,有点复杂,需要慢慢体会这种映射的方法。

代码有两个难点:

1.插入迭代器:

http://www.cnblogs.com/Jadon97/p/6884067.html

2.set_union() , set_intersection.

首先元素在内部要排好序,set显然满足这一点。

代码参考刘汝佳第五章例题

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <set>
 5 #include <vector>
 6 #include <string>
 7 #include <map>
 8 #include <queue>
 9 #include <stack>
10 #include <algorithm>
11 #include <sstream>
12 
13 #define ALL(x) x.begin(),x.end()
14 #define INS(x) inserter(x,x.begin())
15 using namespace std;
16 typedef set<int> Set;
17 map<Set, int> IDcache;
18 vector<Set> Setcache;
19 int ID (Set x)
20 {
21     if(IDcache.count(x)) return IDcache[x];
22     Setcache.push_back(x);
23     return IDcache[x] = Setcache.size() - 1; //都是空集, 唯一区别就是大小
24 }
25 int main()
26 {
27 //    freopen("1.txt","r",stdin);
28     int t;
29     cin>>t;
30     while(t--)
31     {
32         IDcache.clear();
33         Setcache.clear();
34         stack<int> s;
35         int n;
36         cin>>n;
37         for(int i = 0 ; i < n ; i++)
38         {
39             string op;
40             cin >> op;
41             if(op[0] == 'P')
42                s.push(ID(Set()));
43             else if(op[0] == 'D')
44                 s.push(s.top());
45             else
46             {
47                 Set x1 = Setcache[s.top()];
48                 s.pop();
49                 Set x2 = Setcache[s.top()];
50                 s.pop();
51                 Set x;
52                 if(op[0] == 'U') set_union(ALL(x1),ALL(x2),INS(x));
53                 if(op[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x));
54                 if(op[0] == 'A')
55                 {
56                     x=x2;
57                     x.insert(ID(x1));
58                 }
59                 s.push(ID(x));
60             }
61              cout<< Setcache[s.top()].size() <<endl;
62         }
63         cout<<"***"<<endl;
64     }
65 }
原文地址:https://www.cnblogs.com/Jadon97/p/6877791.html