UVA_12096: The SetStack Computer

本文介绍了一种使用栈数据结构来实现集合操作的方法,包括并集、交集和添加等操作,并通过分配唯一ID来简化集合的管理和操作。

点击查看原题

分析:本题的集合并不是数字或字母,而是集合的集合。我们不妨给每个集合分配唯一的ID,则每个集合都可以表示成所包含元素的ID集合,这就可以用set<int>来表示了,而整个栈则是stack<int>,注意这里所谓的ID并不是真实的数字,而是集合数组的标号。


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

#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())

using namespace std;

typedef set<int> Set;
map<Set,int> IDcache;
vector<Set> Setcache;
stack<int> stk;

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,n;
	cin >> T;
	while(T--)
	{
		cin >> n;
		string op;
		while(n--)
		{
			cin >> op;
			if(op[0]=='P')stk.push(ID(Set()));
			else if(op[0]=='D') stk.push(stk.top());
			else{
				Set x1 = Setcache[stk.top()]; stk.pop();
				Set x2 = Setcache[stk.top()]; stk.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));}
				stk.push(ID(x));
			}
			cout << Setcache[stk.top()].size() << endl;
		}
		cout << "***" << endl;
	}
    return 0;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值