Lost Cows(树状数组)

Lost Cows(树状数组)

思路:第k小排名问题,树状数组。因为第 i i i头牛的排名是前 i − 1 i-1 i1头牛比他小的个数加后 i + 1 ∼ n i+1\sim n i+1n比他小的个数再加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=cnt1i1+cnti+1n+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;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酷酷的Herio

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值