解题思路:本题是集合的集合,通过唯一的ID编号(int)对应于相应的集合,typedef set<int> set1 自定义集合类型,map<set1,int>映射出ID; 把所有不相同的集合存放在vector<set1> vec容器当中, 然后通过ID号获得集合(vec[id])。
- #include<cstdio>
- #include<string>
- #include<map>
- #include<set>
- #include<vector>
- #include<stack>
- #include<algorithm>
- #include<iostream>
- using namespace std;
- #define ALL(x) x.begin(),x.end() //宏
- #define INS(x) inserter(x,x.begin())
- typedef set<int> set1; //自定义集合类型
- map<set1,int>mp; //把集合印成ID
- vector<set1>vec; //根据ID取集合
- int ID(set1 s){ //查找给定集合s的ID,如果找不到,分配一个新的ID
- if(mp.count(s))return mp[s];
- vec.push_back(s);
- mp[s]=vec.size()-1;
- return mp[s];
- }
- int main(){
- int T;
- scanf("%d",&T);
- while(T--){
- stack<int>st;
- int n;
- scanf("%d",&n);
- for(int i=0;i<n;i++){
- string str;
- cin>>str;
- if(str[0]=='P')st.push(ID(set1()));
- else if(str[0]=='D')st.push(st.top());
- else {
- set1 s1=vec[st.top()];st.pop();
- set1 s2=vec[st.top()];st.pop();
- set1 s;
- if(str[0]=='U') set_union(ALL(s1),ALL(s2),INS(s));
- if(str[0]=='I') set_intersection(ALL(s1),ALL(s2),INS(s));
- if(str[0]=='A'){
- s=s2,s.insert(ID(s1));
- }
- st.push(ID(s));
- }
- cout<<vec[st.top()].size()<<endl;
- }
- cout<<"***"<<endl;
- }
- return 0;
- }
本题旨在锻炼思维,其中内容涉及到宏,超出了目前为止我所学的,所以我们现在只需理解成“类似于函数的东西”
另外用到STL中内置的集合操作(set_union和 set_intersection)位于头文件<algorithm>中.