计蒜客 校长的问题 树状数组

 

#include<bits/stdc++.h>

using namespace std;

const int maxn=1e5+10;

int C[maxn],ans[maxn],a[maxn];

struct node{
    int a,b,pos;
};

node p[maxn];

int n,m;

bool cmp(const node &x,const node &y ){
    return x.a<y.a;
}

inline int lowbit(int x){
    return x&-x;
}

void change(int p, int x){
    for(;p<=n;p+=lowbit(p)){
        C[p]+=x;
    }
}

int getsum(int x){
    int res=0;
    for(;x;x-=lowbit(x)){
        res+=C[x];
    }
    return res;
}

int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        p[i].a=x;
        p[i].b=y;
        p[i].pos=i;
    }
    sort(p+1,p+m+1,cmp);
    int cnt=1;
    for(int i=1;i<=n;i++){
        change(a[i],1);
        while(p[cnt].a==i){
            ans[p[cnt].pos]=getsum(p[cnt].b);
            cnt++;
        }
    }
    for(int i=1;i<=m;i++){
        printf("%d\n",ans[i]);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40679299/article/details/81699164