题意:模拟一个集合堆栈机,初始化为空,有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;
}