UVa - 12096 The SetStack Computer(STL容器综合,强推!)

题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=42064

#include <iostream>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <vector>
#include <stack>

#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
using namespace std;
/***************************************************************************************************************
        题意:利用栈模拟一些操作
        学习:
        1,不定长数组vector,集合set,映射map,栈stack的综合应用,非常好的一道题
        2,
           a,利用set符合集合的特性来做集合的容器
           b,利用映射来给每个集合设置唯一的编号 id
           c,利用不定长数组和集合编号 id 可以轻易的访问到每个集合
           d,将每个集合的编号入栈,保存处理极为方便
        3,
            algorithm库里面的内置交集,并集函数,注意参数和用法
        4,
            刚开始很难想到怎么处理空集,最后明白,空集也是一种特殊的集合,在全局定义一个set,将它作为一个
            特殊集合处理即可,初始化空集编号为-1
        5,
            一个小技巧:
            对于输入的每条指令,如果首字母可以当作唯一标识字符。
            那么可用 op[0] == 'P' 代替 op == "PUSH";这样可能会降低消耗吧,毕竟比较两个string要调用C++库函数的

***************************************************************************************************************/

set<int> Set;      //集合,利用set的 1,不重复性 (恰好就是集合的特性)
map<set<int>,int > ID;       //集合和集合编号一一对应,每个集合有唯一的编号。空集编号为-1
vector<set<int> > Setcache;      //根据id取集合


int fuc(set<int> x)
{
    if(ID.count(x))     //如果集合 x 已经保存过,直接返回编号
        return ID[x];
    Setcache.push_back(x);      //否则将集合入队列 Setcache 且映射集合编号
    return ID[x]=Setcache.size()-1;     //映射集合编号,从0开始
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        int n;
        cin>>n;
        stack <int> s;      //栈,将集合编号入栈
        for(int i = 1;i <= n;i ++){
            string op;
            cin>>op;

            if(op[0] == 'P')
                s.push(fuc(Set));
            else if(op[0] == 'D')
                s.push(s.top());
            else{
                set<int> x1=Setcache[s.top()];
                s.pop();
                set<int> x2=Setcache[s.top()];
                s.pop();
                set<int> 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(fuc(x1));
                }
                s.push(fuc(x));
            }
            cout<<Setcache[s.top()].size()<<endl;
        }
        cout<<"***"<<endl;
    }
    return 0;
}



 

转载于:https://www.cnblogs.com/Jstyle-continue/p/6351976.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值