个人博客stack(栈),一种符合“后进先出”原则的数据结构。有push和pop两种操作,其中push把元素压入栈顶,pop从栈顶把元素“弹出”。
使用栈需在头文件<stack>,用stack<int>s,声明一个整数型的栈,s.push()压栈,s.pop()出栈,s.top()取栈顶元素(不删除)。
分析:
1.题目给定5种操作,每次输出栈顶集合的元素的个数
2.利用stack和set来模拟,set保存集合的元素。遇到push的时候直接在stack里面push入一个空的set,遇到Dup的时候把栈顶的集合在push进stack一次,遇到union的时候把栈顶的两个集合合并,遇到Intersect的时候把栈顶的两个集合进行求交集然后push进stack,遇到Add的时候要注意如果第一个集合是空集那么我们就认为是在第二个集合里面加入2,否则就要通过map来判断当前的集合所表示的值
set定义一个集合,然后用map为每个集合分配一个ID,然后根据ID取集合。
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]; //如果找到,就返回ID Setcache.push_back(x); //如果找不到,就添加集合 return IDcache[x]=Setcache.size()-1; }
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; }
原文地址:洪学林个人博客:www.hongxuelin.com