Lost Cows(树状数组)
思路:第k小排名问题,树状数组。因为第 i i i头牛的排名是前 i − 1 i-1 i−1头牛比他小的个数加后 i + 1 ∼ n i+1\sim n i+1∼n比他小的个数再加1
即 a n s i = c n t 1 ∼ i − 1 + c n t i + 1 ∼ n + 1 ans_i=cnt_{1\sim i-1}+cnt_{i+1\sim n}+1 ansi=cnt1∼i−1+cnti+1∼n+1.
所以可以用后往前算每次算出 a n s i ans_i ansi,然后用该排名更新树状数组中含有该排名的 t r e e [ ] . tree[]. tree[].
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=1e5+5;
#define mst(a) memset(a,0,sizeof a)
#define lx x<<1
#define rx x<<1|1
#define reg register
#define lowbit(x) (x&-x)
int tr[N],pre[N],ans[N],n;
inline void add(int x,int d){
while(x<=n){
tr[x]+=d;
x+=lowbit(x);
}
}
inline void read(int &x){
x=0;
char ch;
for(ch=getchar();ch<'0'||ch>'9';ch=getchar());
for(;ch>='0'&&ch<='9';ch=getchar())
x=(x<<3)+(x<<1)+(ch&15);
}
inline int sum(int x){
int sum=0;
while(x>0){
sum+=tr[x];
x-=lowbit(x);
}
return sum;
}
int fun(int x){
int l=1,r=n;
while(l<r){
int mid=(l+r)>>1;
if(sum(mid)<x) l=mid+1;
else r=mid;
}
return l;
}
int main(){
read(n),tr[1]=1;
for(reg int i=2;i<=n;i++) read(pre[i]),tr[i]=lowbit(i);
for(reg int i=n;i>0;i--){
int x=fun(pre[i]+1);
add(x,-1);
ans[i]=x;
}
for(reg int i=1;i<=n;i++) printf("%d\n",ans[i]);
return 0;
}