【刘汝佳书】例题5-5 UVA12096 (stack、map的练习)

自己的想法:用set<string>来存集合,把括号当成字符串中的字符
结果:超时,遂抄书上代码

map<set, int>为集合建立ID,再用vector<set>根据ID取集合,这两个要学会

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

using namespace std;

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

typedef set<int> Set;

map<Set, int> IDcache;  //把集合映射成ID
vector<Set> Setcache;   //根据ID取集合
stack<int> s;           //装集合ID的栈

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

int main()
{
    //freopen("C:\\Users\\Summer\\Desktop\\input.txt", "r", stdin);
    //freopen("C:\\Users\\Summer\\Desktop\\output.txt", "w", stdout);

    int test_num, opre_num;
    string opre;
    cin>>test_num;
    while(test_num--) {
        while(!s.empty()) s.pop();

        cin>>opre_num;
        while(opre_num--) {
            cin>>opre;
            if(opre == "PUSH") {
                s.push(getID(Set()));
            }
            else if(opre == "DUP") {
                s.push(s.top());
            }
            else {
                Set a = Setcache[s.top()]; s.pop();
                Set b = Setcache[s.top()]; s.pop();
                Set c;

                if(opre[0] == 'U')      set_union(ALL(a), ALL(b), INS(c));
                else if(opre[0] == 'I') set_intersection(ALL(a), ALL(b), INS(c));
                else {  //opre == "ADD"
                    c = b;
                    c.insert(getID(a));
                }
                s.push(getID(c));
            }

            cout<< Setcache[s.top()].size() <<endl;
        }
        cout<<"***"<<endl;
    }
    return 0;
}

【2019.4.4】
昨晚,被Verilog暴捶了一通,说被打得满地找牙也不为过,
上一次深夜绝望还是美赛的前一晚面对空荡荡的word,
昨天自己做了几道例题,觉得自己写的还可以,
今天爬起来看了看书上的解法,脸都被打肿了,
再看看昨天写的博客,恨不得自杀谢罪,
太菜了,实在是太菜了……

昨天还在听《像暗杀似的绕到背后突然拥抱你》
今天,听《瞎子》

我以后再也不飘了

猜你喜欢

转载自blog.csdn.net/qq_41727666/article/details/89023780