题解:SP1835 SETSTACK - The SetStack Computer

· · 题解

题意

维护一个集合栈,支持集合交并运算和集合簇。

刚开始读题的时候把初始为空栈看成了一个空集合。

分析

首先,集合满足互异性。

直接使用 STL 实现栈和集合,集合中存下标,栈中存集合。因为栈中的集合要能独立运算,所以可以直接存。但是集合中显然不能存集合,只能存数值。为了去重我们需要保证下标的获取是依赖于这个集合的 hash 值。

我们考虑用 map 维护集合是否重复。

接下来就可以模拟了。

实现

复杂度不用考虑,正常写都可以的(写太复杂还不好调)。

巧用特性。

#include<bits/stdc++.h>
using namespace std;
const int N = 2010;
stack<set<int>> stk;
map<set<int>,int> id;
set<int> a,b,c;
int cnt;
unordered_map<string,int> mp;
void get(set<int> s)
{
    if(!id.count(s)) id[s] = ++ cnt;
}
int main()
{
    mp["PUSH"] = 0,mp["DUP"] = 1,mp["UNION"] = 2,mp["INTERSECT"] = 3,mp["ADD"] = 4;
    int t;
    cin>>t;
    while(t --)
    {
        id.clear();
        cnt = 0;
        int n;
        cin>>n;
        while(n --)
        {
            string str;
            cin>>str;
            if(!mp[str]) get(c),stk.push(c);
            else if(mp[str] == 1) a = stk.top(),stk.push(a);
            else if(mp[str] == 2)
            {
                a = stk.top(),stk.pop();
                b = stk.top(),stk.pop();
                for(auto x : a) b.insert(x);
                get(b),stk.push(b);
            }
            else if(mp[str] == 3)
            {
                a = stk.top(),stk.pop();
                b = stk.top(),stk.pop();
                for(auto x : a)
                    if(b.count(x)) c.insert(x);
                get(c),stk.push(c),c.clear();
            }
            else if(mp[str] == 4) a = stk.top(),stk.pop(),b = stk.top(),stk.pop(),b.insert(id[a]),get(b),stk.push(b);
            cout<<stk.top().size()<<'\n';
        }
        puts("***");
    }
    return 0;
}