#include<iostream>
#include<string>
#include<set>
#include<map>
#include<stack>
#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;
map<Set,int> IDcache; // 把集合映射成ID
vector<Set> Setcache; // 根据ID取集合
// 查找给定集合x的ID。如果找不到,分配一个新ID
int ID (Set x) {
if (IDcache.count(x)) return IDcache[x];
Setcache.push_back(x); // 添加新集合
return IDcache[x] = Setcache.size() - 1;
}
int main () {
int T;
cin >> T;
while(T--) {
stack<int> s; // 题目中的栈
int n;
cin >> n;
for(int i = 0; i < n; i++) {
string op;
cin >> op;
if (op[0] == 'P') s.push(ID(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();
Set x;
if (op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x));
if (op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x));
if (op[0] == 'A') { x = x2; x.insert(ID(x1)); }
s.push(ID(x));
}
cout << Setcache[s.top()].size() << endl;
}
cout << "***" << endl;
}
return 0;
}
知识点:1.typedef用来为复杂的声明定义简单的别名,它与宏定义有些差异。
它本身是一种存储类的关键字,与auto、extern、mutable、static、
register等关键字不能出现在同一个表达式中。
2.STL内置的操作:
(1) set_union(class InputIterator1, class InputIterator2 , class outputIterator)
构造两个交集的并集,其中包含在任何一个集合中出现过的元素
(2) set_intersection(class InputIterator1, class InputIterator2 , class outputIterator)
构造两个集合的交集,其中包含在两个集合中都出现过的元素
问题:
1.到底Set中存放的是什么东西?
回答:Set中存放的是大集合
2.map , vector , set ,stack , 每个容器在这道题中的作用?
(1) map:可以从大set映射到大set的ID (ID用来表示每个不同的集合)
(2) vector:每一行就是一个大的set,每一行的大小就是题目所求集合的大小
(3) set:用来存放大小集合
(4) stack:栈中存放每个集合的ID,根据指令操作弹出和删除相应集合
3.这四个容器之间如何相互联系?
map根据大集合映射到大集合的ID;vector的每一行代表一个大集合,
vector的每一行的size代表大集合的大小,vector的每一行的下标代表
不同的元素。
栈中存放的是大集合的ID,入栈根据map查找到ID将ID压入,出栈根
据vector查找到对应的set,实现题中要求的求交集并集等操作
4.map内保存的int值是小集合的ID还是大集合的ID?
大集合的
5.重:vector在里面起什么作用
vector起到从ID查找到对应set实现题中要求的交集并集等操作,并从size
中提供所求的集合的大小
栈的相关操作:https://blog.csdn.net/forward627/article/details/52314544
s.push(item); //将item压入栈顶
s.pop(); //删除栈顶的元素,但不会返回
s.top(); //返回栈顶的元素,但不会删除
s.size(); //返回栈中元素的个数
s.empty(); //检查栈是否为空,如果为空返回true,否则返回false