這個感覺有點難,集合套在映射裡,集合套在不定長數組裡,主要是把集合整體了解。
棧:
stack<int> s定義棧
push()入棧
pop()出棧
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<set>
#include<stack>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
typedef set<int> Set;//把set<int> 等效成Set,把set<int> 轉化成Set類型
map<Set, int> IDcache;//定義map,是Set類型到int的映射,即一個集合,一個ID
vector<Set> Setcache;//定義不定長數組,不定長數組的每個元素是Set類型
//即這是一個不定長的集合的數組
//查找給定的集合x的ID,如果找不到,配置設定一個新的ID
int ID(Set x) {
if(IDcache.count(x)) return IDcache[x];
//在map裡count(查找)集合x,如果找到傳回這個集合的ID
Setcache.push_back(x);//找不到的話向不定長的集合數組添加新的集合
return IDcache[x] = Setcache.size() - 1;
//傳回這個集合的ID,即不定長集合數組的大小-1
}
#define ALL(x) x.begin(),x.end()
#define INS(s) inserter(x,x.begin())
int main()
{
int t;
scanf("%d", &t);
while(t--) {
stack<int> s;//定義一個棧s,這個棧裡存放的是每個集合的ID
//每個集合都可以表示成所包含元素的ID的集合
int n;
cin >> n;
for(int i=0; i<n; i++)
{
string op;//讀入每一條操作
cin >> op;
if(op[0] == 'P') s.push(ID(Set()));//PUSH空集入棧,Set()就表示這是空集
else if(op[0] == 'D') s.push(s.top());//DUP,把目前的棧頂元素入棧
else {//其他的操作
Set x1 = Setcache[s.top()]; s.pop();
Set x2 = Setcache[s.top()]; s.pop();//出棧兩個集合,存放到x1x2中
Set x;//定義一個集合變量x,用來進行中間值
if(op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x));//把集合x1和集合x2的并集存放到x中
//估計集合的存儲像連結清單那樣,所有用x.begin(),x.end()把這個集合的所有元素便利
//inserter(x,x.begin())是從x.begin()開始插入
if(op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x));//把集合x,x2的交集存到x裡
if(op[0] == 'A') { x = x2; x.insert(ID(x1)); }//把集合x1插入到x2中
s.push(ID(x));//把集合x的ID入棧
}
cout << Setcache[s.top()].size() << endl;//輸出對應ID的不定長集合數組的大小
}
printf("***\n");
}
return 0;
}