Advertisement
Saleh127

SPOJ SubXor / Trie

Feb 9th, 2023
673
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. /***
  2.  created: 2023-02-09-16.52.23
  3. ***/
  4.  
  5. #include <bits/stdc++.h>
  6. #include <ext/pb_ds/assoc_container.hpp>
  7. #include <ext/pb_ds/tree_policy.hpp>
  8. using namespace std;
  9. using namespace __gnu_pbds;
  10. template<typename U> using ordered_set=tree<U, null_type,less<U>,rb_tree_tag,tree_order_statistics_node_update>;
  11. #define ll long long
  12. #define all(we) we.begin(),we.end()
  13. #define test int tt; cin>>tt; for(int cs=1;cs<=tt;cs++)
  14. #define nl '\n'
  15.  
  16. const ll  mx=20*100005;
  17.  
  18. ll trie1[mx][2];
  19. ll cnt[mx],sz,k;
  20.  
  21. void insert1(ll x)
  22. {
  23.     ll now=0;
  24.     for(ll i=20; i>=0; i--)
  25.     {
  26.         bool b=(x&(1<<i));
  27.  
  28.         if(trie1[now][b]==0)
  29.         {
  30.             trie1[now][b]=++sz;
  31.         }
  32.         now=trie1[now][b];
  33.         cnt[now]++;
  34.     }
  35. }
  36.  
  37. ll query(ll x)
  38. {
  39.     ll ans=0,now=0;
  40.     for(ll i=20; i>=0; i--)
  41.     {
  42.         bool bk=(k & (1<<i));
  43.         bool bx=(x & (1<<i));
  44.         if(bk)
  45.         {
  46.             ans+=cnt[trie1[now][bx]];
  47.             if(trie1[now][(bx^1)]==0) break;
  48.             now=trie1[now][(bx^1)];
  49.         }
  50.         else
  51.         {
  52.             if(trie1[now][bx]==0) break;
  53.             now=trie1[now][bx];
  54.         }
  55.     }
  56.     return ans;
  57. }
  58.  
  59. int main()
  60. {
  61.     ios_base::sync_with_stdio(0);
  62.     cin.tie(0);
  63.     cout.tie(0);
  64.  
  65.  
  66.     test
  67.     {
  68.         ll n,m,i,j,l=0,ans=0;
  69.  
  70.         cin>>n>>k;
  71.  
  72.         sz=0;
  73.         memset(trie1,0,sizeof trie1);
  74.         memset(cnt,0,sizeof cnt);
  75.         insert1(0);
  76.  
  77.         for(i=0; i<n; i++)
  78.         {
  79.             cin>>m;
  80.             if(i==0)
  81.             {
  82.                 l=m;
  83.                 ans+=query(l);
  84.                 insert1(l);
  85.             }
  86.             else
  87.             {
  88.                 l^=m;
  89.                 ans+=query(l);
  90.                 insert1(l);
  91.             }
  92.         }
  93.  
  94.         cout<<ans<<nl;
  95.     }
  96.     return 0;
  97. }
  98.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement