UVA.12096 The SetStack Computer ( 好题 栈 STL混合应用)

UVA.12096 The SetStack Computer ( 好题 栈 STL混合应用)

题意分析

绝对的好题。
先说做完此题的收获:
1.对数据结构又有了宏观的上的认识;
2.熟悉了常用STL(set,map,vector)的常用用法;
3.学习了一种问题转化的方式。
我想如果告诉我这题用STL解决,并且还能独立完成的话,那么STL应该算是过关了。

有下列操作集:
1.PUSH:向栈顶PUSH一个空集合的元素;
2.DUP: 弹出栈顶元素;
3.UNION: 弹出2个栈顶元素,并且去并集后入栈;
4.INTERSECT:弹出2个栈顶元素,去交集后入栈;
5.ADD:弹出2个栈顶元素,将第一个元素表示的集合加入到第二个元素中。
每次执行完操作,要输出当前栈顶元素中的集合个数,若为空集,则输出0。

我的第一感觉是set类型的stack,但是由于对STL这方面的不熟悉,没有着手实现,而是直接参考了lrj大大的写法。

未完:有时间一定补上题解!!

代码总览

#include <iostream>
#include <set>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <vector>
using namespace std;
typedef map<set<int>,int> Map;
typedef set<int> Set;
vector<Set> IDstore;
Map IDmap;
int findid(Set t)
{
    if(IDmap.count(t) == 1) return IDmap[t];
    IDstore.push_back(t);
    return IDmap[t] = IDstore.size() -1;
}
int main()
{
    //freopen("in.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        stack<int> s;
        int n;
        string ord;
        cin>>n;
        while(n--){
            cin>>ord;
            if(ord[0] == 'P'){
                s.push(findid(Set()));
            }else if(ord[0] == 'D'){
                s.push(s.top());
            }else{
                Set t1 = IDstore[s.top()];s.pop();
                Set t2 = IDstore[s.top()];s.pop();
                Set t;
                if(ord[0] == 'U'){
                    set_union(t1.begin(),t1.end(),t2.begin(),t2.end(),inserter(t,t.begin()));
                }else if(ord[0] == 'I'){
                    set_intersection(t1.begin(),t1.end(),t2.begin(),t2.end(),inserter(t,t.begin()));
                }else if(ord[0] == 'A'){
                    t = t2;
                    t.insert(findid(t1));
                }
                s.push(findid(t));
            }
            cout<<IDstore[s.top()].size()<<endl;
        }
        cout<<"***"<<endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/pengwill/p/7367135.html