Advertisement
istinishat

Trie (binary)

Sep 1st, 2017
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. tutorial : https://threads-iiith.quora.com/Tutorial-on-Trie-and-example-problems
  3. problem : http://codeforces.com/contest/842/problem/D
  4. */
  5. #include<bits/stdc++.h>
  6. using namespace std;
  7.  
  8. #define si(n) scanf("%d",&n)
  9.  
  10.  
  11. struct Trie{
  12.     Trie * nxt0;
  13.     Trie * nxt1;
  14.     int sz;
  15.     Trie() : nxt0(NULL),nxt1(NULL),sz(0){}
  16. };
  17.  
  18. typedef Trie * trie;
  19.  
  20. const int MAX = 3e5+5;
  21. const int MAXLOG =20;
  22.  
  23. int used[MAX];
  24.  
  25. void add(trie root,int n)
  26. {
  27.     root->sz ++;
  28.     for(int i=MAXLOG-1;i>=0;i--){
  29.         if(n & (1<<i)){
  30.             if(root->nxt1 ==NULL)
  31.                 root->nxt1=new Trie();
  32.             root=root->nxt1;
  33.         }
  34.         else{
  35.             if(root->nxt0==NULL)
  36.                 root->nxt0=new Trie();
  37.             root=root->nxt0;
  38.         }
  39.         root->sz++;
  40.     }
  41.  
  42. }
  43.  
  44. int safe_sz(trie a){
  45.     if(!a)return 0;
  46.     return a->sz;
  47. }
  48.  
  49. int mex(trie root)
  50. {
  51.     int ans=0;
  52.     for(int i=MAXLOG-1;i>=0;i--){
  53.         if(root==NULL)return ans;
  54.         if(root->nxt0==NULL && root->nxt1==NULL)
  55.             return ans;
  56.         if(used[i]%2==0){
  57.             if(safe_sz(root->nxt0) != (1<<i))
  58.                 root=root->nxt0;
  59.             else{
  60.                 ans+=(1<<i);
  61.                 root=root->nxt1;
  62.             }
  63.         }
  64.         else{
  65.  
  66.             if (safe_sz(root -> nxt1) != (1 << i)) {
  67.                 root = root -> nxt1;
  68.             }
  69.             else {
  70.                 ans += (1 << i);
  71.                 root = root -> nxt0;
  72.             }
  73.         }
  74.     }
  75.     return ans;
  76. }
  77.  
  78. int main()
  79. {
  80.     int n,m,i,j,p;
  81.     si(n);si(m);
  82.     trie root=new Trie();
  83.     map<int,int>gg;
  84.     while(n--){
  85.         si(p);
  86.         if(++gg[p]==1){
  87.             add(root,p);
  88.         }
  89.     }
  90.  
  91.     for(i=0;i<m;i++){
  92.         si(p);
  93.         for(j=MAXLOG-1;j>=0;j--){
  94.             if(p & (1<<j))
  95.                 used[j]++;
  96.         }
  97.         printf("%d\n",mex(root));
  98.     }
  99.     return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement