题目链接
题意
模拟一个存储元素为“集合”的栈操作,对应以下五个命令,分别有五种操作:
- PUSH:空集“{}”入栈
- DUP:把当前栈顶元素复制一份后再入栈
- UNION:出栈两个集合,然后把二者的并集入栈
- INTERSECT:出栈两个集合,然后把二者的交集入栈
- ADD:出栈两个集合,然后把先出栈的集合作为后出栈的集合的元素,加入到第二个集合中,把结果入栈
每次操作后,输出栈顶集合的大小。
题解
让每一个集合与一个数字一一对应,可以用map< set, int > 和vector< set > 进行快速查找,对于每一个新生成的集合,先在map 中查找之前是否存在,如果不存在,则加入新的集合。
代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <cstdio>
#include <list>
#include <queue>
#include <cstring>
using namespace std;
#define LL long long
vector<set<int> > Vec;
map<set<int>, int> Map;
stack<int> Sta;
vector<int> ans;
void Push() {
Sta.push(0);
cout << 0 << endl;
}
void Dup() {
int tmp = Sta.top();
Sta.push(tmp);
cout << ans[tmp] << endl;
}
void Union() {
int tmp1 = Sta.top();
Sta.pop();
int tmp2 = Sta.top();
Sta.pop();
set<int> stmp1 = Vec[tmp1];
set<int> stmp2 = Vec[tmp2];
set<int>::iterator it;
for(it = stmp1.begin(); it != stmp1.end(); ++it) {
stmp2.insert(*it);
}
if(Map.find(stmp2) == Map.end()) {
Vec.push_back(stmp2);
Map[stmp2] = Vec.size() - 1;
ans.push_back(stmp2.size());
}
Sta.push(Map[stmp2]);
cout << ans[Map[stmp2]] << endl;
}
void Intersect(){
int tmp1 = Sta.top();
Sta.pop();
int tmp2 = Sta.top();
Sta.pop();
set<int> stmp1 = Vec[tmp1];
set<int> stmp2 = Vec[tmp2];
set<int> stmp3;
set<int>::iterator it;
for(it = stmp1.begin(); it != stmp1.end(); ++it) {
if(stmp2.find(*it) != stmp2.end()) {
stmp3.insert(*it);
}
}
if(Map.find(stmp3) == Map.end()) {
Vec.push_back(stmp3);
Map[stmp3] = Vec.size() - 1;
ans.push_back(stmp3.size());
}
Sta.push(Map[stmp3]);
cout << ans[Map[stmp3]] << endl;
}
void Add() {
int tmp1 = Sta.top();
Sta.pop();
int tmp2 = Sta.top();
Sta.pop();
set<int> stmp1 = Vec[tmp1];
set<int> stmp2 = Vec[tmp2];
stmp2.insert(Map[stmp1]);
if(Map.find(stmp2) == Map.end()) {
Vec.push_back(stmp2);
Map[stmp2] = Vec.size() - 1;
ans.push_back(stmp2.size());
}
Sta.push(Map[stmp2]);
cout << ans[Map[stmp2]] << endl;
}
int main()
{
ios::sync_with_stdio(false);
string command;
int T, n;
cin >> T;
while(T--) {
Vec.clear();
Map.clear();
while(!Sta.empty()) Sta.pop();
ans.clear();
Vec.push_back(set<int>());
ans.push_back(0);
Map.insert(pair<set<int>, int>(set<int>(), 0));
cin >> n;
while(n--) {
cin >> command;
switch(command[0]) {
case 'P': Push(); break;
case 'D': Dup(); break;
case 'U': Union(); break;
case 'I': Intersect(); break;
case 'A': Add(); break;
}
}
cout << "***" << endl;
}
return 0;
}