Link: Ultraviolet A 12096-The setstack computer
Five operations are available for one stack;
- Push: place an empty set into the stack.
- DUP: replica stack top set.
- Union: Take the two sets at the top of the stack, take the Union set, and put it back.
- Intersect: Take the two sets at the top of the stack, take the intersection and put it back.
- Add: Take the top two sets of the stack, place the first set as an element in the second set, and put the second set back into the stack.
After each operation, the number of elements in the set of stacks is output.
Solution: map all sets into a value, use map to record, and then simulate the operation.
#include <cstdio>#include <cstring>#include <set>#include <map>#include <stack>#include <algorithm>using namespace std;typedef set<int> sint;typedef set<int>::iterator iter;int hn;stack<sint> stak;map<sint, int> g;void hashadd (sint u) { if (g.count(u)) return; g[u] = hn++;}void putsize () { if (stak.empty()) return; printf("%d\n", (int)stak.top().size());}void sf_push () { sint u; hashadd(u); stak.push(u);}void sf_dup () { sint u = stak.top(); stak.push(u);}void sf_union () { sint f = stak.top(); stak.pop(); sint u = stak.top(); stak.pop(); for (iter i = f.begin(); i != f.end(); i++) u.insert(*i); hashadd(u); stak.push(u);}void sf_inct () { sint u; sint f = stak.top(); stak.pop(); sint s = stak.top(); stak.pop(); for (iter i = f.begin(); i != f.end(); i++) { if (s.count(*i)) u.insert(*i); } hashadd(u); stak.push(u);}void sf_add () { sint f = stak.top(); stak.pop(); sint s = stak.top(); stak.pop(); s.insert(g[f]); hashadd(s); stak.push(s);}void solve () { char order[10]; scanf("%s", order); switch (order[0]) { case ‘P‘: sf_push(); break; case ‘D‘: sf_dup(); break; case ‘U‘: sf_union(); break; case ‘I‘: sf_inct(); break; case ‘A‘: sf_add(); break; } putsize();}int main () { int cas, n; scanf("%d", &cas); while (cas--) { hn = 0; g.clear(); while (!stak.empty()) stak.pop(); scanf("%d", &n); while (n--) solve(); printf("***\n"); } return 0;}
Ultraviolet A 12096-The setstack computer (STL)