UVA - 12096 The SetStack Computer

/*

  注释十分详尽的blog:
  http://blog.csdn.net/a197p/article/details/43407901
  
  思路:
  本题的集合不是简单的整数集合或字符串集合,而是集合的集合,为了方便表示,可以为每个不同的集合分配唯一的ID,则每个集合都可以表示成所包含元素的ID集合
  这样就能用STL的set<int>来表示了,而整个栈就是一个stack<int>
  
  收获:
  1. Set(STL)
  #define ALL(x) x.begin(), x.end()
  #define INS(x) inserter(x, x.begin())
  set_union(ALL(x1), ALL(x2), INS(x))表示x是x1 和 x2 的并集
  set_intersection(ALL(x1), ALL(x2), INS(x)) 表示x是 x1 和 x2 的交集
*/



#include <bits/stdc++.h>
using namespace std;
typedef set<int> Set;
map<Set, int> IDcache; //把集合映射成ID
vector<Set> Setcache; // 根据ID取集合, 元素为集合的不定长数组

//查找给定集合的ID。如果找到了,则返回它的ID,否则,分配一个新ID并返回
//对于任意类型为Set的集合s,IDcache[s]就是它的ID,而 Setcache[IDcache[s]] 就是 s本身
 
int ID (Set x)
{
	if (IDcache.count(x)) return IDcache[x];
	Setcache.push_back(x);
	return IDcache[x] = Setcache.size() - 1;
}

#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())
//这两个宏分别表示 所有的内容 和 插入迭代器,定义这两个宏以后,可以通过 STL 内置的集合操作, set_union 和 set_intersection,来实现集合的取并集和取交集

int main()
{
	stack<int>s;
	int k, n;
	cin >> k;
	while (k--)
	{
//		while (!s.empty()) s.pop();
		cin >> n;
		for (int i = 0; i < n; i++)
		{
			string op;
			cin >> op;
			if (op[0] == 'P') s.push(ID(Set())); //空集入栈,Set()表示空集
			else if (op[0] == 'D') s.push(s.top());
			else
			{
				Set x1 = Setcache[s.top()]; s.pop(); 
				Set x2 = Setcache[s.top()]; s.pop(); // 出栈两个集合,并存放在x1和x2中
				Set x; //定义集合x作为中间变量
				if (op[0] == 'U') set_union(ALL(x1), ALL(x2), INS(x));
				else if (op[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x));
				else if (op[0] == 'A')
				{
					x = x2; x.insert(ID(x1)); //将集合x1对应的ID压栈 
				}
				
				s.push(ID(x)); 
			} 
			cout << Setcache[s.top()].size() << endl; //将栈顶的int型元素ID变为其对应的真正的集合,再求这个集合的大小
		}
		
		cout << "***" << endl; 
		
	} 
	
	return 0;
}


转载于:https://www.cnblogs.com/mofushaohua/p/7789464.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值