poj 2182 lost cows 树状数组,二分

线段树做法

http://www.cnblogs.com/wuyiqi/archive/2011/12/21/2295391.html

从后往前操作

View Code
#include<cstdio>
#include<cstring>
const int maxn = 80001;
int a[maxn],c[maxn],ans[maxn],n;
int lowbit(int x){
return x&-x;
}
void update(int x,int d){
for(;x<maxn;x+=lowbit(x))
c[x]+=d;
}
int sum(int x){
int ans=0;
for(;x>0;x-=lowbit(x))
ans+=c[x];
return ans;
}
int bin(int num){
int l=1,r=n,mid,tmp,best;
while(l<=r){
mid=(l+r)>>1;
tmp=sum(mid);
if(tmp>=num){
best=mid;
r=mid-1;
}
else l=mid+1;
}
return best;
}
int main(){
int i,j;
while(~scanf("%d",&n)){
memset(c,0,sizeof(c));
a[1]=0;update(1,1);
for(i=2;i<=n;i++){
scanf("%d",&a[i]);
update(i,1);
}
for(i=n;i>=1;i--){
int pos=bin(a[i]+1);
ans[i]=pos;
update(pos,-1);
}
for(i=1;i<=n;i++) printf("%d\n",ans[i]);
}
}



你可能感兴趣的:(树状数组)