ismaeil

D. Vasiliy's Multiset

Mar 3rd, 2020
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.14 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. long long getMaxXor(long long);
  6. void addNewNum(long long);
  7. void delOldNum(long long);
  8. struct Trie;
  9. Trie *newNode();
  10.  
  11. struct Trie{
  12.     int cnt;
  13.     Trie *next[2];
  14. }*root = newNode();
  15.  
  16. Trie *newNode(){
  17.     Trie *node;
  18.     node = new Trie;
  19.     node -> cnt = 0;
  20.     node -> next[0] = node -> next[1] = NULL;
  21.     return node;
  22. }
  23.  
  24. long long getMaxXor(long long x){
  25.     int Max = 0;
  26.     Trie *Cur = root;
  27.     for(int i=31 ; i>=0 ; i--){
  28.         int T = x & (1 << i);
  29.         bool idx = T ? 0 : 1;
  30.  
  31.         if(Cur -> next[idx] == NULL){
  32.             if(Cur -> next[!idx] != NULL)
  33.                 idx = !idx;
  34.             else if(Cur -> next[!idx] == NULL)
  35.                 return 0;
  36.         }
  37.  
  38.         Cur = Cur -> next[idx];
  39.         if(idx)
  40.             Max |= ( 1 << i );
  41.     }
  42.     return Max;
  43. }
  44.  
  45. void addNewNum(long long x){
  46.     Trie *Cur = root;
  47.     for(int i=31 ; i>=0 ; i--){
  48.         int T = x & (1 << i);
  49.         bool idx = T ? 1 : 0;
  50.         if(Cur -> next[idx] == NULL){
  51.             Cur -> next[idx] = newNode();
  52.         }
  53.         Cur = Cur -> next[idx];
  54.         Cur -> cnt++;
  55.         //cout << "new " << idx << ' ' << Cur -> cnt << ' ' << i << endl;
  56.     }
  57. }
  58.  
  59. void delOldNum(long long x){
  60.     Trie *Cur = root;
  61.     for(int i=31 ; i>=0 ; i--){
  62.         int T = x & (1 << i);
  63.         bool idx = T ? 1 : 0;
  64.  
  65.         Cur -> next[idx] -> cnt --;
  66.         if(Cur -> next[idx] -> cnt == 0){
  67.             Cur -> next[idx] = NULL;
  68.             break;
  69.         }else{
  70.             Cur = Cur -> next[idx];
  71.         }
  72.     }
  73. }
  74.  
  75. int main()
  76. {
  77.     int Q; cin >> Q;
  78.     while(Q--){
  79.         char ch;
  80.         long long x;
  81.  
  82.         cin >> ch >> x;
  83.         switch(ch){
  84.             case '+':{
  85.                 addNewNum(x);
  86.                 }break;
  87.             case '-':{
  88.                 delOldNum(x);
  89.                 }break;
  90.             case '?':{
  91.                 long long Max = getMaxXor(x);
  92.                 //cout << x << " asd " << Max << endl;
  93.                 cout << (Max^x) << endl;
  94.                 }break;
  95.         }
  96.     }
  97.     return 0;
  98. }
  99. /*
  100. 4
  101. ? 1
  102. + 1
  103. + 4
  104. ? 5
  105. */
Advertisement
Add Comment
Please, Sign In to add comment