Advertisement
RaFiN_

cf-703D

Jan 1st, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.21 KB | None | 0 0
  1. /* We can count the number of distinct elements in a range in O(nlogn) instead of MO's O(n*sqrt(n)) ..For that we have to first run a loop from index 1 to index n . Update in a Segment tree the last position of arr[i] to 0 and update the position i to 1..Then run a loop to all the queries that ends in position i..Query the segment tree how many elements are there  from left to position i..That's our answer!! **/
  2.  
  3. /** In the problem below the same thing is done ..But instead of distinct elements the xor sum of the distinct elements is calculated.So the segment tree is updated by last position of arr[i] to 0 and position i to arr[i] instead of 1..And query the xor sum instead of partial sum.. **/
  4.  
  5. int f[MAX];ll arr[MAX],res[MAX],ans;map<int,int>mm;int a[MAX],b[MAX];vector<pii> v[MAX];ll pre[MAX];map<int,int> last;
  6.  
  7. ll tree[4*MAX];
  8.  
  9. void update(int node,int b,int e,int indx,int val)
  10. {
  11.     if(b>indx||e<indx)return ;
  12.     if(b==e)
  13.     {
  14.         tree[node] = val;
  15.         return ;
  16.     }
  17.  
  18.     int mid = (b+e)>>1;
  19.     int left = 2*node;
  20.     int right = left + 1;
  21.     update(left,b,mid,indx,val);
  22.     update(right,mid + 1,e,indx,val);
  23.     tree[node] = tree[left]^tree[right];
  24. }
  25.  
  26. ll query(int node,int b,int e,int l,int r)
  27. {
  28.     if(b>r||e<l)return 0;
  29.  
  30.     if(b>=l&&e<=r)return tree[node];
  31.     int mid = (b+e)>>1;
  32.     int left = 2*node;
  33.     int right = left + 1;
  34.     ll p1 = query(left,b,mid,l,r);
  35.     ll p2 = query(right,mid + 1,e,l,r);
  36.     return p1^p2;
  37.  
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43.  
  44.     ///read("input.txt");
  45.  
  46.     int n;
  47.     scani(n);
  48.     for(int i = 1;i<=n;i++)scani(arr[i]);
  49.  
  50.     int m;
  51.     scani(m);
  52.  
  53.     for(int i = 1;i<=m;i++)
  54.     {
  55.         scani2(a[i],b[i]);
  56.         v[b[i]].pb(pii(a[i],i));
  57.     }
  58.     int cnt = 1;
  59.  
  60.     for(int i = 1;i<=n;i++)
  61.     {
  62.         pre[i] = pre[i-1]^arr[i];
  63.     }
  64.  
  65.     for(int i = 1;i<=n;i++)
  66.     {
  67.         update(1,1,n,last[arr[i]],0);
  68.         update(1,1,n,i,arr[i]);
  69.         last[arr[i]] = i;
  70.         ll ans = 0;
  71.         for(int j = 0;j<v[i].size();j++)
  72.         {
  73.             ans = pre[i]^pre[v[i][j].ff - 1]^query(1,1,n,v[i][j].ff,i);
  74.             res[v[i][j].ss] = ans;
  75.         }
  76.     }
  77.  
  78.     for(int i = 1;i<=m;i++)printf("%I64d\n",res[i]);
  79.  
  80.     return 0;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement