12096 - The SetStack Computer
来源:互联网 发布:微信小程序 源码下载 编辑:程序博客网 时间:2024/05/17 23:01
代码:
#include<iostream>
#include<algorithm>//使用set_union和set_intersection
#include<vector>
#include<map>
#include<set>
#include<stack>
using namespace std;
#define ALL(x) x.begin(),x.end()//宏定义:表示遍历x的所有内容
#define INS(x) inserter(x,x.begin())//插入迭代器:表示插入到x的开头
typedef set<int> Set;//利用set中元素是互异的
map<Set,int> IDcache;//每一种集合都在映射中有唯一的ID
vector<Set> Setcache;
//每一种不同的集合都存取在该数组中,且集合的ID由集合存取在该数组中的先后顺序决定
int ID(Set x);//获取集合的ID的函数
int main()
{
stack<int> s;//栈:存取每个插入的集合的ID
int test1;
cin>>test1;
while(test1--)
{
int test2;
cin>>test2;
while(test2--)
{
string str;
cin>>str;
if(str=="PUSH")
{
s.push(ID(Set()));//插入一空集,在栈中插入数字0
}
else if(str=="DUP")
{
s.push(s.top());
}
else
{
Set x1=Setcache[s.top()];
s.pop();//删除最顶集合
Set x2=Setcache[s.top()];
s.pop();//再次删除最顶集合
Set x;//将要插入栈中的集合
if(str=="UNION")
{
set_union(ALL(x1),ALL(x2),INS(x));//求并集
}
if(str=="INTERSECT")
{
set_intersection(ALL(x1),ALL(x2),INS(x));//求交集
}
if(str=="ADD")
{
x=x2;
x.insert(ID(x1));
}
s.push(ID(x));
}
cout<<Setcache[s.top()].size()<<endl;//一一对应
}
}
}
int ID(Set x)
{
if(IDcache.count(x))//若已经存取
{
return IDcache[x];
}
Setcache.push_back(x);//没存取
IDcache[x]=Setcache.size()-1;
return IDcache[x];
}
思路解析:
该题的栈不是存取简单的数字或者字符串而是存取集合的集合.为方便起见,将每一种集合映射成唯一的ID来标志,为每个不同的集合分配一个唯一的ID,那么每个集合都可以表示成包含元素的ID集合。各种容器的功能如下:
set<int> :空集({})中没有任何数字,内含一个空集的集合({ {} })存取成{0},因为0是空集({})的ID,也就是说将存取不同集合的集合转化为存取不同集合对应ID数字的集合,转化后便于操作
map<Set,int> IDcache:使用映射来完成将存取不同集合(键)的集合转化为存取不同集合对应ID数字(值)的集合的功能
vector<Set> Setcache:每一种不同的集合都存取在该数组中,且集合的ID由集合存取在该数组中的先后顺序决定
stack<int> s:栈:存取每个插入的集合的ID
- 12096 - The SetStack Computer
- 12096 - The SetStack Computer
- 12096 - The SetStack Computer
- uva 12096 The SetStack Computer
- UVA - 12096 The SetStack Computer
- UVa 12096 - The SetStack Computer
- UVa 12096 The SetStack Computer
- Uva - 12096 - The SetStack Computer
- UVa-12096 The SetStack Computer
- UVA 12096 The SetStack Computer
- uvaoj-12096:the setstack computer
- UVA 12096 - The SetStack Computer
- The SetStack Computer id:12096
- UVa 12096 - The SetStack Computer
- UVA-12096 The SetStack Computer
- UVA 12096 The SetStack Computer
- Uva 12096 The SetStack Computer
- UVa 12096 The SetStack Computer
- 540 - Team Queue
- 814 - The Letter Carrier's Rounds
- 1592 - Database
- 10474 - Where is the Marble
- 10815 - Andy's First Dictionary
- 12096 - The SetStack Computer
- 212 - Use of Hospital Facilities
- HDU 1575 Tr A (矩阵快速幂)
- UVa 11375 Matches
- 230 - Borrowers
- 511 - Do You Know the Way to San Jose
- 822 - Queue and A
- PHP中错误控制@运算符
- 1593 - Alignment of Code