uva12096 The SetStack Computer

解决方法: 哈希+模拟

时间复杂度: \(unknown\)

空间复杂度: \(O(n)\)

思路

这题最关键的一点就是用什么数据结构来表示集合里面嵌套集合,因为C/C++是静态类型语言,而stl中的set容器必须预先声明容器里的类型,所以不能直接使用stl的set。所以可以将通过hash,将每一个集合映射为一个整数,这样就可以递归地表示集合了。后面只需要模拟各种操作即可,集合并、交可以使用stl中的函数完成。

code:

#include<bits/stdc++.h>
using namespace std;
typedef set<int> Set;

map<Set,int> IDCache;
vector<Set> SetCache;
stack<int> s;
int ID(Set x){
    if(IDCache.count(x)) return IDCache[x];
    SetCache.push_back(x);
    return IDCache[x]=SetCache.size()-1;
}
int main(){
#ifndef ONLINE_JUDGE
    freopen("../in.txt","r",stdin);
    freopen("../out.txt","w",stdout);
#endif
    int T,n;
    cin>>T;
    while(T--){
        cin>>n;
        for(int i=0;i<n;++i){
            string op;
            cin>>op;
            if(op[0]=='P') s.push(ID(Set()));
            else if(op[0]=='D') s.push(s.top());
            else{
                Set x1=SetCache[s.top()];s.pop();
                Set x2=SetCache[s.top()];s.pop();
                Set x;
                if(op[0]=='U') set_union(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
                if(op[0]=='I') set_intersection(x1.begin(),x1.end(),x2.begin(),x2.end(),inserter(x,x.begin()));
                if(op[0]=='A') {x=x2;x.insert(ID(x1));}
                s.push(ID(x));
            }
            cout<<SetCache[s.top()].size()<<endl;
        }
        cout<<"***"<<endl;
    }
    return 0;
}
posted @ 2020-06-01 09:29  xcjm  阅读(176)  评论(0)    收藏  举报