The SetStack Computer UVA12096(集合栈计算机)

来源:互联网 发布:软件测试覆盖率 编辑:程序博客网 时间:2024/05/22 09:05
解题思路:本题是集合的集合,通过唯一的ID编号(int)对应于相应的集合,typedef set<int> set1 自定义集合类型,map<set1,int>映射出ID; 把所有不相同的集合存放在vector<set1> vec容器当中, 然后通过ID号获得集合(vec[id])。

  1. #include<cstdio>
  2. #include<string>
  3. #include<map>
  4. #include<set>
  5. #include<vector>
  6. #include<stack>
  7. #include<algorithm>
  8. #include<iostream>
  9. using namespace std;

  10. #define ALL(x) x.begin(),x.end()           //宏
  11. #define INS(x) inserter(x,x.begin())

  12. typedef set<int> set1;     //自定义集合类型
  13. map<set1,int>mp;           //把集合印成ID
  14. vector<set1>vec;              //根据ID取集合

  15. int ID(set1 s){    //查找给定集合s的ID,如果找不到,分配一个新的ID
  16.     if(mp.count(s))return mp[s];
  17.     vec.push_back(s);
  18.     mp[s]=vec.size()-1;
  19.     return mp[s];
  20. }

  21. int main(){
  22.     int T;
  23.     scanf("%d",&T);
  24.     while(T--){
  25.     stack<int>st;
  26.     int n;
  27.     scanf("%d",&n);
  28.     for(int i=0;i<n;i++){
  29.         string str;
  30.         cin>>str;
  31.         if(str[0]=='P')st.push(ID(set1()));
  32.         else if(str[0]=='D')st.push(st.top());
  33.         else {
  34.             set1 s1=vec[st.top()];st.pop();
  35.             set1 s2=vec[st.top()];st.pop();
  36.             set1 s;
  37.             if(str[0]=='U') set_union(ALL(s1),ALL(s2),INS(s));
  38.             if(str[0]=='I') set_intersection(ALL(s1),ALL(s2),INS(s));
  39.             if(str[0]=='A'){
  40.                 s=s2,s.insert(ID(s1));
  41.             } 
  42.             st.push(ID(s));
  43.         }
  44.         cout<<vec[st.top()].size()<<endl;
  45.     }
  46.     cout<<"***"<<endl;
  47.     }
  48.     return 0;
  49. }

本题旨在锻炼思维,其中内容涉及到宏,超出了目前为止我所学的,所以我们现在只需理解成“类似于函数的东西”
另外用到STL中内置的集合操作(set_union和 set_intersection)位于头文件<algorithm>中.

0 0
原创粉丝点击