习题:校长的问题

版权声明:转载记得标明出处哦~ https://blog.csdn.net/weixin_43890047/article/details/88853586

题目:校长的问题

询问的是[1 ~ a]排列中有多少个排名小于等于b的个数,一般这样的问题都是维护每个数字出现多少次的树状数组,只要把后面的数都加上1就可。(其实就是访问到一个数字后,在这个数字对应区间加1,在后面询问的时候就询问1~q(询问值)即可)
而这道题有另外一个问题,询问访问的位置不规律。则将访问点a进行排序。每过一点维护一次树状数组,一直维护到当访问排序a,用getsum求出其在1~a的前b位,再把询问下标存在ans下标,询问结果存在ans里

代码
#include<bits/stdc++.h>
using namespace std;

const int MAX_N = 100050;
int state[MAX_N];		///
int c[MAX_N];               ///用于维护[1~a]的树状数组。将询问q存储起来,按a排序
int ans[MAX_N];

struct node
{
    int a;
    int b;
    int pos;
}Q[MAX_N];

bool cmp(const node &n1,const node &n2)
{
    return n1.a<n2.a;
}

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

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

int change(int x)
{
    for(x;x<=MAX_N;x+=lowbit(x))
    {
        c[x]++;
    }
}

int main()
{
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%d",&state[i]);
    }
    for(int i=1;i<=m;i++){
        int a,b;
        scanf("%d%d",&a,&b);
        Q[i].a = a;
        Q[i].b = b;
        Q[i].pos = i;
    }
    sort(Q+1,Q+m+1,cmp);
    int cnt =1;
    for(int i=1;i<=n;i++){
        change(state[i]);
        while(Q[cnt].a==i)         ///因为结构体已经按a排过序了,所以一定会遍历所有结构体(a从低到高)
        {
            ans[Q[cnt].pos] = getsum(Q[cnt].b);
            cnt++;
        }
    }
    for(int i=1;i<=m;i++){
        printf("%d\n",ans[i]);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/weixin_43890047/article/details/88853586
今日推荐