bzoj 3289: Mato的文件管理

莫队加树状数组

  1 #include<cstdio>
  2 #include<iostream>
  3 #include<cstring>
  4 #include<cstdlib>
  5 #include<cmath>
  6 #include<queue>
  7 #include<algorithm>
  8 #include<vector>
  9 #define M 2000009
 10 #define EPS 1e-10
 11 #define MO 10000
 12 #define ll long long
 13 using namespace std;
 14 ll read()
 15 {
 16     char ch=getchar();
 17     ll x=0,f=1;
 18     for(;ch<'0'||ch>'9';ch=getchar())
 19         if(ch=='-')
 20           f=-1;
 21     for(;ch>='0'&&ch<='9';ch=getchar())
 22         x=x*10+ch-'0';
 23     return x*f;
 24 }
 25 int belong[M],n,a[M],q,m,h[M],ans[M];
 26 int shu[M],shu1[M];
 27 struct data
 28 {
 29     int x,y,id;
 30 }b[M];
 31 bool cmp(data a1,data a2)
 32 {
 33     if(belong[a1.x]==belong[a2.x])
 34       return a1.y<a2.y;
 35     return belong[a1.x]<belong[a2.x];
 36 }
 37 int xun(int x)
 38 {
 39     int sum=0;
 40     for(;x;x-=x&-x)
 41       sum+=shu[x];
 42     return sum;
 43 }
 44 int xun1(int x)
 45 {
 46     int sum=0;
 47     for(;x;x-=x&-x)
 48       sum+=shu1[x];
 49     return sum;
 50 }
 51 void jia(int x)
 52 {
 53     for(;x<h[0];x+=x&-x)
 54       shu[x]++;
 55 }
 56 void jia1(int x)
 57 {
 58     for(;x<h[0];x+=x&-x)
 59       shu1[x]++;
 60 }
 61 void jian(int x)
 62 {
 63     for(;x<h[0];x+=x&-x)
 64       shu[x]--;
 65 }
 66 void jian1(int x)
 67 {
 68     for(;x<h[0];x+=x&-x)
 69       shu1[x]--;
 70 }
 71 int main()
 72 {
 73     n=read();
 74     for(int i=1;i<=n;i++)
 75       h[i]=a[i]=read();
 76     sort(h+1,h+n+1);
 77     h[0]=unique(h+1,h+n+1)-h;
 78     for(int i=1;i<=n;i++)
 79       a[i]=lower_bound(h+1,h+h[0],a[i])-h;
 80     q=read();
 81     for(int i=1;i<=q;i++)
 82       {
 83           b[i].x=read();
 84           b[i].y=read();
 85           b[i].id=i;
 86       }
 87     m=sqrt(n);
 88     for(int i=1;i<=q;i++)
 89       belong[i]=i/m+1;
 90     sort(b+1,b+q+1,cmp);
 91     int l=0,r=0,sum=0;
 92     for(int i=1;i<=q;i++)
 93       {
 94         for(;r<b[i].y;r++)
 95           {
 96             sum+=xun1(h[0]-a[r+1]);
 97             jia1(h[0]-a[r+1]);
 98             jia(a[r+1]);
 99           }
100         for(;r>b[i].y;r--)
101           {
102             jian1(h[0]-a[r]);
103             jian(a[r]);
104             sum-=xun1(h[0]-a[r]);
105           }
106         for(;l<b[i].x;l++)
107           {
108             if(!l)
109               continue;
110             jian(a[l]);
111             jian1(h[0]-a[l]);
112             sum-=xun(a[l]);
113           }
114         for(;l>b[i].x;l--)
115           {
116             sum+=xun(a[l-1]);
117             jia(a[l-1]);
118             jia1(h[0]-a[l-1]);
119           }
120         ans[b[i].id]=sum;
121       }
122     for(int i=1;i<=q;i++)
123       printf("%d\n",ans[i]);
124 }
125 

 

posted @ 2016-07-09 20:32  xiw5  阅读(130)  评论(0编辑  收藏  举报