標籤:
題目連結: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; //集合和集合編號一一對應,每個集合有唯一的編號。空集編號為-1vector<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;}
UVa - 12096 The SetStack Computer(STL容器綜合,強推!)