4eyes4u

Mo's algorithm

Sep 19th, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. /*
  2. Koliko ima l<=i<j<=r tako da je XOR[i..j]=K
  3. */
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7.  
  8. const int N=1e5+10;
  9. const int Q=1e6+10;
  10. const int LIM=(1<<20)+10;
  11. const int BLOCK_SIZE=320;
  12. const int BLOCKS=320;
  13.  
  14. int ksor[N];
  15. long long sol[N], tot;
  16. int cnt[LIM];
  17. int n, k, q;
  18.  
  19. struct Query
  20. {
  21.     int l, r, idx;
  22.     bool operator<(const Query &p) const
  23.     {
  24.         return r<p.r;
  25.     }
  26. };
  27.  
  28. vector<Query> v[BLOCKS];
  29.  
  30. void add (int x)
  31. {
  32.     tot+=1ll*cnt[x^k];
  33.     cnt[x]++;
  34. }
  35.  
  36. void del (int x)
  37. {
  38.     cnt[x]--;
  39.     tot-=1ll*cnt[x^k];
  40. }
  41.  
  42. int main()
  43. {
  44.     scanf ("%d%d%d", &n, &q, &k);
  45.  
  46.     for (int i=1;i<=n;i++)
  47.     {
  48.         int a;
  49.         scanf ("%d", &a);
  50.         ksor[i]=ksor[i-1]^a;
  51.     }
  52.     for (int i=1;i<=q;i++)
  53.     {
  54.         Query xt=*new Query();
  55.         xt.idx=i;
  56.         scanf ("%d%d", &xt.l, &xt.r);
  57.         xt.l--; xt.r++;
  58.         v[xt.l/BLOCK_SIZE].push_back(xt);
  59.     }
  60.  
  61.     for (int i=0;i<BLOCKS;i++) sort (v[i].begin(), v[i].end());
  62.  
  63.     for (int i=0;i<BLOCKS;i++)
  64.     {
  65.         int levo=i*BLOCK_SIZE;
  66.         int desno=i*BLOCK_SIZE;
  67.  
  68.         for (auto xt: v[i])
  69.         {
  70.             while (desno<xt.r)
  71.             {
  72.                 add (ksor[desno]);
  73.                 desno++;
  74.             }
  75.             while (levo>xt.l)
  76.             {
  77.                 levo--;
  78.                 add (ksor[levo]);
  79.             }
  80.             while (levo<xt.l)
  81.             {
  82.                 del (ksor[levo]);
  83.                 levo++;
  84.             }
  85.  
  86.             sol[xt.idx]=tot;
  87.         }
  88.  
  89.         for (int j=levo;j<desno;j++) del(ksor[j]);
  90.     }
  91.  
  92.     for (int i=1;i<=q;i++) printf ("%lld\n", sol[i]);
  93.  
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment