mihaimarcel21

median_query

Feb 20th, 2021 (edited)
822
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. ifstream fin("median_query.in");
  4. ofstream fout("median_query.out");
  5. struct Cell
  6. {
  7.     int val,poz;
  8.     bool operator < (const Cell &Next) const
  9.     {
  10.         return val < Next.val;
  11.     }
  12. };
  13. Cell VN[100005];
  14. int WVN[100005];
  15. int vec[100005], Buck_size;
  16. struct Query
  17. {
  18.     int l, r, Pozo;
  19.     bool operator < (const Query &Next) const
  20.     {
  21.         if(l / Buck_size == Next.l / Buck_size)
  22.             return r < Next.r;
  23.         return l / Buck_size < Next.l / Buck_size;
  24.     }
  25. } queries[100005];
  26. int ans[100005];
  27. int N, Q;
  28. struct AIB
  29. {
  30.     int v[100005];
  31.     void update(int node,int val)
  32.     {
  33.         for(int i=node;i<=N;i+=(i&(-i)))
  34.             v[i]+=val;
  35.     }
  36.     int query(int node)
  37.     {
  38.         int s=0;
  39.  
  40.         for(int i=node;i>=1;i-=(i&(-i)))
  41.             s+=v[i];
  42.         return s;
  43.     }
  44.     int CBinary(int val)
  45.     {
  46.         int step=(1<<17);
  47.         int poz=0;
  48.         while(step)
  49.         {
  50.             if(poz+step<=N && v[poz+step]<val)
  51.                 val-=v[poz+step],poz+=step;
  52.             step/=2;
  53.         }
  54.         return poz+1;
  55.     }
  56. } aib;
  57.  
  58. void ADD(int poz)
  59. {
  60.     aib.update(vec[poz],1);
  61. }
  62.  
  63. void DEL(int poz)
  64. {
  65.     aib.update(vec[poz],-1);
  66. }
  67.  
  68. int main()
  69. {
  70.     fin>>N>>Q;
  71.     Buck_size=sqrt(N);
  72.     for(int i=1;i<=N;++i)
  73.     {
  74.         int x;
  75.         fin>>x;
  76.         VN[i].val=x;
  77.         VN[i].poz=i;
  78.     }
  79.     sort(VN+1,VN+N+1);
  80.     for(int i=1;i<=N;++i)
  81.     {
  82.         vec[VN[i].poz]=i;
  83.         WVN[i]=VN[i].val;
  84.     }
  85.     for(int i=1;i<=Q;++i)
  86.     {
  87.             fin>>queries[i].l>>queries[i].r;
  88.             queries[i].Pozo=i;
  89.     }
  90.     sort(queries+1,queries+Q+1);
  91.     int st=1,dr=0;
  92.     for(int i=1;i<=Q;++i)
  93.     {
  94.         int l,r;
  95.         l=queries[i].l;
  96.         r=queries[i].r;
  97.         while(dr<r)
  98.             ++dr,ADD(dr);
  99.         while(st<l)
  100.             DEL(st),++st;
  101.         while(st>l)
  102.             --st,ADD(st);
  103.         while(dr>r)
  104.             DEL(dr),--dr;
  105.         int med=(r-l+2)/2;
  106.         ans[queries[i].Pozo]=WVN[aib.CBinary(med)];
  107.     }
  108.     for(int i=1;i<=Q;++i)
  109.         fout<<ans[i]<<'\n';
  110.     return 0;
  111. }
  112.  
Add Comment
Please, Sign In to add comment