UVA-12096
栈中的元素是集合的集合,把每个集合映射一个ID,由于元素是集合的集合,每个集合又能看作是ID的集合。
栈中存放ID,在vector中根据ID取到相应的集合,集合里存放的是子元素集合的ID。每一个ID对应一种唯一的集合类型。
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <stack>
using namespace std;
#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())
typedef set<int> Set;
map<Set, int> IDMap;
vector<Set> setCache;
int getID(Set s) {
if (IDMap[s]) {
return IDMap[s];
}
setCache.push_back(s);
IDMap[s] = setCache.size() - 1;
return IDMap[s];
}
int main() {
int n;
scanf("%d", &n);
while (n--) {
int m;
scanf("%d", &m);
string op;
stack<int> s;
setCache.clear();
IDMap.erase(ALL(IDMap));
for (int i = 0; i < m; ++i) {
cin >> op;
if (op[0] == 'P') {
s.push(getID(Set()));
} else if (op[0] == 'D') {
s.push(s.top());
} else {
Set s1 = setCache[s.top()];
s.pop();
Set s2 = setCache[s.top()];
s.pop();
Set s3;
if (op[0] == 'U') {
set_union(ALL(s1), ALL(s2), INS(s3));
}
if (op[0] == 'I') {
set_intersection(ALL(s1), ALL(s2), INS(s3));
}
if (op[0] == 'A') {
s3 = s2;
s3.insert(getID(s1));
}
s.push(getID(s3));
}
cout << setCache[s.top()].size() << endl;
}
cout << "***\n";
}
return 0;
}