stack 集合棧電腦 (摘)

來源:互聯網
上載者:User

標籤:

有一個專門為了集合運算而設計的“集合棧”電腦。該機器有一個初始為空白的棧,並且支援以下操作:
PUSH:空集“{}”入棧
DUP:把當前棧頂元素複製一份後再入棧
UNION:出棧兩個集合,然後把兩者的並集入棧
INTERSECT:出棧兩個集合,然後把二者的交集入棧
ADD:出棧兩個集合,然後把先出棧的集合加入到後出棧的集合中,把結果入棧
       每次操作後,輸出棧頂集合的大小(即元素個數)。例如棧頂元素是A={ {}, {{}} }, 下一個元素是B={ {}, {{{}}} },則:
UNION操作將得到{ {}, {{}}, {{{}}} },輸出3.
INTERSECT操作將得到{ {} },輸出1
ADD操作將得到{ {}, {{{}}}, { {}, {{}} } },輸出3.

輸入不超過2000個操作

Sample Input

9
PUSH
DUP
ADD
PUSH
ADD
DUP
ADD
DUP
UNION

Sample Output

0
0
1
0
1
1
2
2
2

 

#include<iostream>#include<string>#include<algorithm>#include<iterator>#include<vector>#include<set>#include<map>#include<stack>using namespace std;typedef set<int> Set;          map<Set,int> IDcache;           //把集合映射成IDvector<Set> Setcache;    int ID(Set x)              //尋找給定集合x的ID,如果找不到,分配一個新ID{    if(IDcache.count(x))return IDcache[x];    Setcache.push_back(x);             //添加新集合    return IDcache[x]=Setcache.size()-1;}#define ALL(x) x.begin(),x.end()#define INS(x) inserter(x,x.begin())int main() {    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()];          //top()取棧頂元素(但不刪除)            s.pop();                           //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;    }    system("pause");    return 0;}

 

stack 集合棧電腦 (摘)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.