BZOJ1932 [Shoi2007]Setstack 集合堆栈机

题意:模拟一个集合堆栈机,初始化为空,有5种指令:

PUSH:把一个空集压入栈。

DUP:复制栈顶,入栈。

UNION:取出栈顶前两个,把它们的并集入栈。

INTERSECT:取出栈顶前两个,把它们的交集入栈。

ADD:取栈顶为S,再取栈顶为T,把T∪{S}入栈。

一共n(0 <= n <= 2000)条指令,每条指令输出栈顶集合的元素个数。

时间限制:1000ms

总通过时间:1336ms

分析:首先整个题目就是一个栈,我们先开个栈,之后我们不能模拟一个真正的集合,于是我们想到把它们映射成数字,自然要用到map,用一个id函数来得到它的映射值。

PUSH和DUP操作很简单,不详细介绍,我们考虑后三个操作,因为我要求交并,所以由映射值得得到真实的集合,用vector来存储。

<algorithm>里封装了两个函数是set_union和set_intersection,用于求集合的并和交。

用法是set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), inserter(x, x.begin())),set_intersection用法类似,这里用了宏来简化代码。

尝试着去提交了一下,发现TLE,怎么优化呢?

经过gzz神犇的指点,map里多加了一个cmp的构造函数,用于比较set的大小,因为据说默认的set比较特别慢,加了之后过了,gzz神神神...

#include <cstdio>
#include <stack>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())

typedef set<int> Set;
struct cmp {
	bool operator () (const Set &a, const Set &b) {
		if(a.size() != b.size()) return a.size() < b.size();
		Set::iterator ita = a.begin(), itb = b.begin();
		while(ita != a.end() && *ita == *itb) ++ita, ++itb;
		if(ita == a.end()) return false;
		return *ita < *itb;
	}
};

char str[10];
int T, n;
stack<int> st;
map<Set, int, cmp> mp;
vector<Set> v;

int id(Set x) {
	if(mp[x] != 0) return mp[x];
	v.push_back(x);
	return mp[x] = v.size() - 1;
}

int main() {
	scanf("%d", &n);
	while(n--) {
		scanf("%s", str);
		if(str[0] == 'P') st.push(id(Set()));
		else if(str[0] == 'D') st.push(st.top());
		else {
			Set x1 = v[st.top()]; st.pop();
			Set x2 = v[st.top()]; st.pop();
			Set x;
			if(str[0] == 'U') set_union(ALL(x1), ALL(x2), INS(x));
			else if(str[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x));
			else x = x2, x.insert(id(x1));
			st.push(id(x));
		}
		printf("%d\n", v[st.top()].size());
	}
	return 0;
}


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值