您的位置:首页 > 其它

UVa_The SetStack Computer

2017-03-19 11:01 197 查看

题址:12096 - The SetStack Computer

题意:

对一系列集合进行栈操作;

PUSH: 空集 {} 入栈;

DUP: 栈顶集合复制一份入栈;

UNION: 出栈栈顶两集合,然后把两者合并入栈;

INTERSECT: 出栈栈顶两集合,然后两者交集入栈;

ADD: 出栈栈顶两集合,先出栈的集合加入到后出栈集合,然后入栈;

每次操作输出栈顶集合大小;

思路:

代码:

#include <iostream>
#include <cstdio>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <set>
#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取集合

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

int main()
{
int t;
scanf("%d", &t);
while(t--)
{
stack<int> s;
int n;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
string str;
cin >> str;
if(str[0] == 'P') s.push(ID(Set()));
else if(str[0] == 'D') s.push(s.top());
else
{
Set s1 = Setcache[s.top()]; s.pop();
Set s2 = Setcache[s.top()]; s.pop();
Set x;
if(str[0] == 'U') set_union(ALL(s1), ALL(s2), INS(x));
if(str[0] == 'I') set_intersection(ALL(s1), ALL(s2), INS(x));
if(str[0] == 'A') {x = s2; x.insert(ID(s1));}
s.push(ID(x));
}
printf("%d\n", Setcache[s.top()].size());
}
printf("***\n");
}
return 0;
}


// WA:

#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>
#include <map>
#include <vector>
#include <stack>
#include <set>
#include <algorithm>

using namespace std;

#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())
int main()
{
int t;
cin >> t;
while(t--)
{
stack<set<int>> s1;
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
string str;
cin >> str;
if(str[0] == 'P') s1.push(set<int>());
else if(str[0] == 'D') s1.push(s1.top());
else
{
set<int> s2 = s1.top(); s1.pop();
set<int> s3 = s1.top(); s1.pop();
set<int> s4;
if(str[0] == 'U') set_union(ALL(s2), ALL(s3), INS(s4));
if(str[0] == 'I') set_intersection(ALL(s2), ALL(s3), INS(s4));
if(str[0] == 'A') {s4 = s3; s4.insert(s2.size());}
s1.push(s4);
}
cout << s1.top().size() << '\n';
}
cout << "***" << '\n';
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  uva