Advertisement
Misbah_Uddin_Tareq

MO's algo

Apr 15th, 2020
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. #define pb push_back
  5. #define ff first
  6. #define ss second
  7. const int mx=200002;
  8.  
  9. int k,ans[mx],a[mx],sum=0;
  10. struct Query
  11. {
  12.     int index,l,r;
  13.     bool operator<(const Query& other)
  14.     {
  15.         int block_own = l/k;
  16.         int block_other = other.l/k;
  17.         if(block_own == block_other)
  18.             return r < other.r;
  19.         return block_own < block_other;
  20.     }
  21. } query[mx];
  22.  
  23. void add(int index)
  24. {
  25.     sum+=a[index];
  26. }
  27.  
  28. void remove(int index)
  29. {
  30.     sum-=a[index];
  31. }
  32.  
  33. int main()
  34. {
  35.     int n;
  36.     cin>>n;
  37.     k=sqrt(n);
  38.     for(int i=0; i<n; i++)
  39.     {
  40.         cin>>a[i];
  41.     }
  42.  
  43.     int q;
  44.     cin>>q;
  45.     for(int i=0; i<q; i++)
  46.     {
  47.         cin>>query[i].l>>query[i].r;
  48.         query[i].index = i;
  49.     }
  50.     sort(query,query+q);
  51.  
  52.     int l=0,r=-1;
  53.     for(int i=0; i<q; i++)
  54.     {
  55.         while(r<query[i].r) add(++r);
  56.         while(l<query[i].l) remove(l++);
  57.         while(r>query[i].r) remove(r--);
  58.         while(l>query[i].l) add(--l);
  59.         ans[query[i].index]=sum;
  60.     }
  61.  
  62.     for(int i=0; i<q; i++)
  63.         cout<<ans[i]<<"\n";
  64.  
  65.     return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement