这道题能在《算法经典(第二版)》上找到,不贴图了。
看了看书,发现书比我自己想到的好多了。
苟蒻在此跪拜 刘汝佳大神。
#include<cstdio> #include<cstring> #include<cstdlib> #include<set> #include<map> #include<vector> #include<stack> #include<algorithm> using namespace std; #define ALL(x) x.begin(), x.end() #define INS(x) inserter(x, x.begin()) typedef set<int> Set; map<Set, int> idcard; vector<Set> setid; stack<int> s; int n; int get_id(Set x) { if (idcard.count(x)) return idcard[x]; setid.push_back(x); return idcard[x] = setid.size() - 1; } int main() { int Test; scanf("%d", &Test); while (Test--) { scanf("%d", &n); while (!s.empty()) s.pop(); setid.clear(); idcard.clear(); while (n--) { char cmd[10]; scanf("%s", &cmd); if (cmd[0] == 'P') s.push(get_id(Set())); else if (cmd[0] == 'D') s.push(s.top()); else { Set x1 = setid[s.top()]; s.pop(); Set x2 = setid[s.top()]; s.pop(); Set x; if (cmd[0] == 'U') set_union(ALL(x1), ALL(x2), INS(x)); if (cmd[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x)); if (cmd[0] == 'A') { x = x2; x.insert(get_id(x1)); } s.push(get_id(x)); } printf("%d ", setid[s.top()].size()); } printf("*** "); } return 0; }