ch_POJ2182 Lost Cows

利用树状数组求第k大的数

具体就是标101010101010........

统计1个数也就是前缀和

#include<iostream>
#include<cstdio>

#define ri register int
#define u long long

namespace opt {

    inline u in() {
        u x(0),f(1);
        char s(getchar());
        while(s<'0'||s>'9') {
            if(s=='-') f=-1;
            s=getchar();
        }
        while(s>='0'&&s<='9') {
            x=(x<<1)+(x<<3)+s-'0';
            s=getchar();
        }
        return x*f;
    }

}

using opt::in;

#define NN 200005

#include<cstring>

namespace mainstay {

    u N,K;

    u c[NN],ans[NN],a[NN];

    inline u ask(const u &x) {
        u _re(0);
        for(ri i(x); i; i-=i&-i) _re+=c[i];
        return _re;
    }

    inline void add(const u &x,const u &y) {
        for(ri i(x); i<=N; i+=i&-i) c[i]+=y;
    }

    inline void solve() {
        N=in();
        for(ri i(2); i<=N; ++i) a[i]=in();
        for(ri i(1);i<=N;++i) add(i,1);
        for(ri i(N);i>=1;--i){
            u l(a[i]+1),r(N),mid,ans1;
            while(l<=r){
                mid=(l+r>>1);
                if(ask(mid)>=a[i]+1) r=mid-1,ans1=mid;
                else l=mid+1;
            }
            ans[i]=ans1,add(ans1,-1);
        }
        for(ri i(1);i<=N;++i) printf("%d
",ans[i]);
    }

}

int main() {

    //freopen("x.txt","r",stdin);
    std::ios::sync_with_stdio(false);
    mainstay::solve();

}
原文地址:https://www.cnblogs.com/ling-zhi/p/11783002.html