例题5-5 集合栈计算机(The SetStack Computer,ACM/ICPC NWERC 2006,UVa12096)

原题链接:https://vjudge.net/problem/UVA-12096
分类:<stack>
备注:stack与STL其他容器的综合运用
前言:第一次看这些真是一脸懵逼,set还有这种操作?STL综合运用这么神奇?因为这个题我才了解到空集作为元素原来是这样的…对,代码几乎就是从作者那里搬来的,不用怀疑。

  set_union是取并集的函数,set_intersection的取交集的函数,此外还有取差集,对称差集(环和)的函数,这些函数的参数都是一样的。头文件是<algorithm>。
  inserter函数:插入迭代器。头文件是<iterator>。需要把集合A,B运算后得到的结果插入集合C时(相当于集合C就是运算结果),使用该函数。

思路

  • 建立元素为set<int>的vector,对于每个新出现的集合,如果vector中没有该集合,则用map映射给该集合一个编号,并且将该集合存入vector中,这个编号即是该集合在vector中所在位置的下标。
  • 建立stack<int>,其中存放的是集合的编号,不同集合的编号是没有重复的,每种集合也只有一个编号。
  • 利用取交集和取并集的函数进行操作。
  • 理解好set<int>中的元素含义,set<int>中的元素是用编号来代替的集合(和上面的stack一样),set<int>是集合族,元素个数即是集合个数。
  • 利用vector找到栈顶(栈顶即下标)对应的set<int>,set自带取元素个数的操作,set.size()。

代码如下:

#include<cstdio>
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<algorithm>
#include<iterator>
using namespace std;
int T, N;
set<int>Set;
map<set<int>, int>xb;
vector<set<int> >Set_store;

int ID(set<int> x)
{
	if (xb.count(x))return xb[x];
	Set_store.push_back(x);
	return xb[x] = Set_store.size() - 1;
}

int main(void)
{
	scanf("%d", &T);
	while (T--)
	{
		stack<int>st;
		scanf("%d", &N); getchar();
		while (N--)
		{
			char cmd[10]; scanf("%s", cmd);
			if (cmd[0] == 'P')st.push(ID(set<int>()));//建立空集的操作
			else if (cmd[0] == 'D')st.push(st.top());
			else
			{
				set<int>x1 = Set_store[st.top()]; st.pop();
				set<int>x2 = Set_store[st.top()]; st.pop();
				set<int>x;
				if (cmd[0] == 'U')set_union(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));//取并集
				if (cmd[0] == 'I')set_intersection(x1.begin(), x1.end(), x2.begin(), x2.end(), inserter(x, x.begin()));//取交集
				if (cmd[0] == 'A')x = x2, x.insert(ID(x1));
				st.push(ID(x));
			}
			printf("%d\n", Set_store[st.top()].size());
		}
		printf("***\n");
	}
	return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JILIN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值