集合棧計算機(UVa12096)

 

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

 

算法流程以下:ios

 

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 }
相關文章
相關標籤/搜索