標籤:
The SetStack Computer
PS:因為該題排版較麻煩,這裡給出OJ網址:UVa12096 - The SetStack Computer
有一個專門為了集合運算而設計的“集合棧”電腦。該機器有一個初始為空白的棧,並且支援以下操作。
- PUSH:空集“{}”入棧。
- DUP:把當前棧頂元素複製一份後再入棧。
- UNION:出棧兩個集合,然後把二者的並集入棧。
- INTERSECT:出棧兩個集合,然後把二者的交集入棧。
- ADD:出棧兩個集合,然後把先出棧的集合加入到後出棧的集合中,把結果入棧。
每次操作後,輸出棧頂集合的大小(即元素個數)。例如,棧頂元素是A={{},{{}}},下一個元素是B={{},{{{}}}},則:
- UNION操作將得到{{},{{}},{{{}}}},輸出3。
- INTERSECT操作將得到{{}},輸出1。
- ADD操作將得到{{},{{{}}},{{},{{}}}},輸出3。
輸入不超過2000個操作,並且保證操作均能順利進行(不需要對空棧執行出棧操作)。
#include <iostream>#include <string>#include <stack>#include <set>#include <map>#include <vector>#include <algorithm>using namespace std;// 設計思路:// map只能擷取key->value這樣的關聯// 如果想通過value->key就必須再添加另一種輔助容器// 在這是通過vector容器實現value->key,也就是說具有以下關係// idCache[x] 為集合x的id// setCache[idCache[x]] 就是x集合本身// set<int>為集合,int為idmap<set<int>, int> idCache;// 緩衝set集合vector<set<int> > setCache;// 尋找給定集合s的ID,如果未找到,分配一個新IDint ID(set<int> s) { if(idCache.count(s)) { return idCache[s]; } // 將集合x加入到set緩衝中 setCache.push_back(s); // 將集合x在緩衝中的位置,作為唯一ID return idCache[s] = setCache.size() - 1;}int main() { int T; cin >> T; while(T--) { // 集合棧 stack<int> s; int n; cin >> n; for(int i = 0; i < n; i++) { // 操作 string op; cin >> op; // PUSH if(op[0] == ‘P‘) { // 將空集入棧 s.push(ID(set<int>())); } else if(op[0] == ‘D‘) { // DUP // 將棧頂元素再次入棧 s.push(s.top()); } else { // 取出棧頂的兩個元素 set<int> x1 = setCache[s.top()]; s.pop(); set<int> x2 = setCache[s.top()]; s.pop(); set<int> x; // UNION if(op[0] == ‘U‘) { // 1,2參數為集合x1的元素開始結束位置迭代器 // 3,4參數為集合x2的元素開始結束位置迭代器 // 5參數代表插入迭代器 set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin())); } // INTERSECT if(op[0] == ‘I‘) { set_intersection(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin())); } // ADD if(op[0] == ‘A‘) { x = x2; x.insert(ID(x1)); } s.push(ID(x)); } cout << setCache[s.top()].size() << endl; } cout << "***" << endl; } return 0;}
12096 - The SetStack Computer