uva12096集合栈计算机
预备知识
set
1.求交集:
int a[5]={1,2,3,4,5};
int b[5]={4,5,6,7,8};
vector<int> c(10);//一定要指定大小,否则会无法运行
vector<int>::iterator it;
it=set_union(a,a+5,b,b+5,c.begin());//set_union返回最后一个元素后的地址,自动去重
/*或者it=set_union(a.begin(),a.end(),a.begin(),a.end(),inserter( c , c.begin() ) );
inserter()的第二个参数是一个指向给定容器的迭代器。元素将被插入到给定迭代器所表示的元素之前*/
cout<<it-c.begin()<<endl;//输出8
for(it=c.begin();it!=c.end();it++)
cout<<*it<<" ";
2.求并集:
set_intersection(a.begin(),a.end(),b.begin(),b.end(),inserter(c,c.begin()));//最后一个参数不可用c.begin(),否则会无法运行,也不可令it=set_union
宏定义
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
题目
PUSH:向栈中放一个空集合。
DUP:复制栈顶集合。
UNION:取栈顶的两个集合,取并集后放回。
INTERSECT:取栈顶的两个集合,取交集后放回。
ADD:取栈顶两个集合,将顶集合作为元素放到第二个集合中,并将第二个集合放回栈。
每次操作后输出栈定集合中元素的个数。
DUP:复制栈顶集合。
UNION:取栈顶的两个集合,取并集后放回。
INTERSECT:取栈顶的两个集合,取交集后放回。
ADD:取栈顶两个集合,将顶集合作为元素放到第二个集合中,并将第二个集合放回栈。
每次操作后输出栈定集合中元素的个数。
代码
#include <set>
#include <iterator>
#include <algorithm>
#include <stack>
#include <string>
#include <vector>
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
using namespace std;
typedef set<int> Set;//默认构造函数Set()创造一个空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, n;
cin >> t;
while (t--) {
stack<int>s;//集合栈只存放集合的ID
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)); //set_union求两个set容器的交集
if (op[0] == 'I') set_intersection(ALL(x1), ALL(x2), INS(x)); //set_intersection求两个set容器的并集
if (op[0] == 'A') {
x = x2;
x.insert(ID(x1));//set对象insert()后其实排序了
}
s.push(ID(x));
}
cout << Setcache[s.top()].size() << endl;//输出每一步操作后栈顶集合的元素的个数。
}
cout << "***" << endl;
}
return 0;
}

浙公网安备 33010602011771号