紫书5-UVA-12096-集合栈计算机-stack,map技巧

本文介绍了一种复杂的集合操作模拟方法,通过将集合映射为整数ID,实现对集合进行并集、交集和添加等操作。使用C++实现,详细展示了如何通过栈、映射和集合数据结构来跟踪和更新集合状态。

在这里插入图片描述
在这里插入图片描述

题意:

定义了5种操作,模拟相应操作即可

思路:

本题集合中存放的还是集合,故需要特殊方法,将每个集合映射到一个int编号,此题比较复杂,要仔细思考,详见代码
注意此题这种特殊处理方法,思路很重要

代码:

#include <iostream>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <algorithm>
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())

using namespace std;
typedef set<int>Set;                //Set中存放此集合包含的其它集合的id
map<Set,int> IDcache;            //将一个set映射到唯一的一个id
vector<Set> Setcache;            //通过id找到相应集合

int ID(Set x)        //寻找id,若没有即是新集合,为其生成一个新id
{
    if(IDcache.count(x))
        return IDcache[x];
    Setcache.push_back(x);
    return IDcache[x]=Setcache.size()-1;
}


int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        IDcache.clear();
        Setcache.clear();
        stack<int>s;
        int n;
        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(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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ogmx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值