UVa 12096 The SetStack Computer

本题的集合并不是简单的整数集合或者字符串集合,而是集合的集合(一个比较抽象的问题)。为了方便起见,此处为每个不同的集合分配一个唯一的ID,则可以将集合的集合转化为int类型的集合。整个栈是一个stack<int>。

有多组数据的时候要初始化栈!

#include<iostream>
#include<cstdio>
#include<stack>
#include<set>
#include<map>
#include<vector>
#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;   //在查找元素ID的时候有用 
vector<Set> Setcache;   //根据集合取ID,因为ID是数,所以直接用数组 
stack<int> s;
int n,m;

int ID (Set x) {
	if (IDcache.count(x)) return IDcache[x];
	Setcache.push_back(x);
	return IDcache[x] = Setcache.size() - 1;  //与上一个语句相对应 
}

int main()
{
	cin>>n;
	while (n-- && cin >> m) {
		while (m--) {
			string op;
			cin>>op;
			if (op[0] == 'P') s.push(ID(Set ()));   //每次只取第一个字母判断,减少程序时间 
			else if (op[0] == 'D') s.push(s.top());
			else {
				Set s1 = Setcache[s.top()]; s.pop();
				Set s2 = Setcache[s.top()]; s.pop();
				Set x;
				if (op[0] == 'U') set_union (ALL(s1), ALL(s2), INS(x));
				if (op[0] == 'I') set_intersection (ALL(s1), ALL(s2), INS(x));
				if (op[0] == 'A') {
					x = s2; x.insert(ID(s1)); //Set是int类型的集合,里面存储的是各个集合的ID编号 
				}
				s.push(ID(x));
			}
			cout<< Setcache[s.top()].size() << endl;
		}
		cout<<"***"<<endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值