集合栈计算机
1.使用的容器说明
集合set——设置空集合
映射map——保存各类空集合(关键key为集合,value为ID,实现了不同种类的集合能找到自己的ID)
数组vector——元素为集合,但因为vector有下标的功能,因此用下标作为不同种类集合的ID(很巧妙,注意这种思想)
栈stack——集合栈,元素为集合
2.源代码
//2020年3月30日17:38:15
//栈的使用 集合的定义方法和处理方法
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
//定义两个宏,用来做并集和交集运算
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x, x.begin())
using namespace std;
typedef set<int> Set;//集合的定义,内部可以存储int变量,不同的int代表不同种类的集合
map<Set, int> IDcache;//保存不同种类的集合,用int类型表示
vector<Set> Setcache;//为不同种类的集合分配ID
//查找给定集合x的ID,如果找不到,分配一个新的ID(注意分配方法)
int ID(Set x){
if (IDcache.count(x)) return IDcache[x];//利用map集合的count方法,确定指定的key(集合x)是否存在
//不存在,分配ID
Setcache.push_back(x);//将新的类型的集合添加分配ID的vector中
return IDcache[x] = Setcache.size() - 1;//直接利用该vector容器的大小来分配ID,实现了Setcache的索引就是其元素Set的ID
}
int main()
{
stack<int> s;//定义需要使用的栈,内部存放int变量,其中int为集合的类型,间接实现了用栈存放集合
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();//出栈,保存第一个出栈元素给x1
Set x2 = Setcache[s.top()];
s.pop();//出栈,保存第一个出栈元素给x2
Set x;//临时变量x,保存对x1,x2进行操作后的结果
if (op[0] == 'U'){//并集操作
set_union(ALL(x1), ALL(x2), INS(x));//并集后的结果给x
}
if (op[0] == 'I'){//交集操作
set_intersection(ALL(x1), ALL(x2), INS(x));//交集后的结果给x
}
if (op[0] == 'A'){
x = x2;
x.insert(ID(x1));//set集合中添加元素的方式insert
}
s.push(ID(x));
}//!else
cout << Setcache[s.top()].size() << endl;
}//!for
return 0;
}
3.总结
1.此程序对空集合的创建和使用的思想很巧妙,要多加重视和研究,以后可以应用在其他更复杂的数据类型的处理上,很实用的一种思想。
2.对各类容器的使用要熟练掌握。
3.对于宏的定义和使用以及set_union和set_intersection还不清楚,日后继续研究。