UVa-12096 Collection Stack Computer (STL)

【Title】

There is a "set stack" computer designed specifically for set operations. The machine has an initially empty stack and supports the following operations:
PUSH: push the empty set "{}" onto the stack
DUP: copy the current top element of the stack and push it into the stack
UNION: pop two sets, and then push the two sets INTERSECT: pop the two sets
from the stack, then push the intersection of the two, and output the size of the intersection
ADD: pop the two sets, and then pop the first set Add to the set that is popped from the stack, push the result onto the stack, and output the size of the result.
       After each operation, output the size of the set at the top of the stack (that is, the number of elements). For example, the top element of the stack is A={ {}, {{}} }, and the next element is B={ {}, {{{}}} }, then:
UNION operation will get { {}, {{}}, {{{}}} }, output 3.
INTERSECT operation will get { {} }, output 1
ADD operation will get { {}, {{{}}}, { {}, {{}} } }, output 3 .

Other operations output 0

 

Multiple groups of input and output, output a line of "***" after each group of output

Enter no more than 2000 actions

Sample Input

2
9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION
5
PUSH
PUSH
ADD
PUSH
INTERSECT

Sample Output

0
0
1
0
1
1
2
2
2
***
0
0
1
0
0
***

【Code】

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <algorithm>
using namespace std;

#define ALL(x) x.begin(), x.end()
 #define INS(x) inserter(x, x.begin()) 
//I feel that these two macros are really powerful typedef set<int> Set; map<Set, int> IDcache; vector<Set> Setcache; int ID(Set x) //find the representative id of set x in the list { if (IDcache.count(x)) return IDcache[x]; Setcache.push_back(x);//If not found, add a new one return IDcache[x] = Setcache.size()-1; } intmain () { int T; cin >> T; while(T--) { IDcache.clear(); Setcache.clear(); stack<int> s; int n; scanf("%d", &n); for (int i = 1; i <= n; i++) { string opr; cin >> opr; if (opr[0] == 'P') s.push(ID(Set())); else if (opr[0] == 'D') s.push(s.top()); else { Set x, y, sum; x = Setcache[s.top()]; s.pop(); y = Setcache[s.top()]; s.pop(); if (opr[0] == 'U') set_union(ALL(x), ALL(y), INS(sum));
            //set_union() merge x and y into sum
else if (opr[ 0 ] == ' I ' ) set_intersection(ALL(x), ALL(y), INS(sum));
            //set_intersection ( ) finds the intersection of x and y, and stores it in sum
else if (opr[ 0 ] == ' A ' ) { sum = y; sum.insert(ID(x));//Instead of combining the two sets, x is an element of y } s.push(ID(sum)); } printf("%d\n", Setcache[s.top()].size()); } printf("***\n"); } }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325117903&siteId=291194637