分析:STL中栈(stack)的操作
思路:
本题的集合不是简单的整数集合或者字符串集合,而是集合的集合。在这里,用map为每一个不同的集合分配一个唯一的ID, 则每个集合可以表示成所包含元素的集合,这样就可以使用STL 中的set来表示了,整个栈则是一个stack.
知识点:
1.栈就像一口深井, 先进的总得最后才能出来;队列就像一条隧道,先进的可以先走到出口;
2.STL的头文件stack提供了栈,用“stack s”定义。用push( )和pop( )进行元素的入栈和出栈操作,top( )取栈顶元素;
3.难理解的地方:定义的两个宏是为了代码的简化.
set_union( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first );
set_intersection( InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first );
代码:
#include<iostream>
#include<algorithm> //set_union; set_intersection都放在这个头文件里
#include<map>
#include<vector>
#include<set>
#include<stack> //栈的头文件
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x, x.begin())//两个宏,分别表示所有内容和插入迭代器
using namespace std;
typedef set<int> Set; //重定义类型Set
map<Set,int > IDcache;
vector <Set> Setcache;
int ID(Set x)
{
if(IDcache.count(x)) return IDcache[x]; //如果map中出现集合x,就返回它对应的整数
Setcache.push_back(x); //如果不存在x,在不定数组后边加上集合X
return IDcache[x] = Setcache.size() - 1; //返回在MAP中x对应的整数为不定数组的大小-1
}
int main()
{
int T; //第几个case
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;
}