uva 12096 The SetStack Computer(STL)


题目大意:

PUSH:向栈中放一个空集合。

DUP:复制栈顶集合。

UNION:取栈顶的两个集合,取并集后放回。

INTERSECT:取栈顶的两个集合,取交集后放回。

ADD:取栈顶两个集合,将第一个集合作为元素放到第二个集合中,并将第二个集合放回栈。

解体思路:

用每个数字代表不同的集合,用放入容器中的顺序代表集合的数字



#include<stdio.h>
#include<stack>
#include<algorithm>
#include<set>
#include<vector>
#include<map>
#include<iostream>
#include<string>
using namespace std;

typedef set<int> Set;
map<Set,int> IDcache;
vector<Set> Setcache;

int ID(Set x){
    if(IDcache.count(x)) return IDcache[x];
    Setcache.push_back(x);
    return IDcache[x]=Setcache.size()-1;
}

#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())

stack<int> s;

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&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(ALL(x1),ALL(x2),INS(x));
                if(op[0]=='I') set_intersection(ALL(x1),ALL(x2),INS(x));
                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 @ 2016-09-27 16:30  hong-ll  阅读(198)  评论(0编辑  收藏  举报