UVA-12096 集合栈 map+stack+set

51 篇文章 2 订阅

UVA-12096
栈中的元素是集合的集合,把每个集合映射一个ID,由于元素是集合的集合,每个集合又能看作是ID的集合。
栈中存放ID,在vector中根据ID取到相应的集合,集合里存放的是子元素集合的ID。每一个ID对应一种唯一的集合类型。

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <stack>
using namespace std;
#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())
typedef set<int> Set;
map<Set, int> IDMap;
vector<Set> setCache;
int getID(Set s) {
	if (IDMap[s]) {
		return IDMap[s];
	}
	setCache.push_back(s);
	IDMap[s] = setCache.size() - 1;
	return IDMap[s];
}
int main() {
	int n;
	scanf("%d", &n);
	while (n--) {
		int m;
		scanf("%d", &m);
		string op;
		stack<int> s;	
		setCache.clear();
		IDMap.erase(ALL(IDMap));
		for (int i = 0; i < m; ++i) {
			cin >> op;
			if (op[0] == 'P') {
				s.push(getID(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 s3;
				if (op[0] == 'U') {
					set_union(ALL(s1), ALL(s2), INS(s3));
				}
				if (op[0] == 'I') {
					set_intersection(ALL(s1), ALL(s2), INS(s3));
				}
				if (op[0] == 'A') {
					s3 = s2;
					s3.insert(getID(s1));
				}
				s.push(getID(s3));
			}
			cout << setCache[s.top()].size() << endl;
		}
		cout << "***\n";
	}
	return 0;
}
`stack->data[++stack->top1] = value` 和 `stack->data[stack->top1++] = value` 是两种不同的写法,但在这个特定的情况下,它们实际上是等价的。 假设 `top1` 的初始值为 0,并且执行这两个语句之前, `stack` 已经被正确初始化。那么,这两个语句都将把 `value` 存储到 `stack->data[0]` 中,并将 `top1` 的值增加 1。 下面是对这两个语句的解释和执行过程: 1. `stack->data[++stack->top1] = value`: - `++stack->top1` 表达式会先对 `top1` 的值进行自增操作,然后返回自增后的结果(即先执行 `++stack->top1`,再使用该值)。 - 执行完 `++stack->top1` 后,`top1` 的值变为 1。 - 然后,将 `value` 存储到 `stack->data[1]` 中。 2. `stack->data[stack->top1++] = value`: - `stack->top1++` 表达式会先使用 `top1` 的当前值,然后再对 `top1` 的值进行自增操作。 - 首先,将 `value` 存储到 `stack->data[0]` 中(因为此时 `top1` 的值仍为 0)。 - 然后,执行完 `stack->top1++` 后,`top1` 的值变为 1。 在这个特定的情况下,无论使用哪种写法,最终结果都是将 `value` 存储到 `stack->data[0]` 中,并将 `top1` 的值增加到 1。因此,这两种写法在功能上是等效的。 需要注意的是,这种等效性只在这个特定的语句中成立。在其他上下文中,这两种写法可能会产生不同的结果。因此,在编写代码时,根据具体的语义和需求选择适当的写法是很重要的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值