首页 > 编程语言 > 详细

树状数组奆

时间:2021-07-13 15:07:43      阅读:10      评论:0      收藏:0      [点我收藏+]

树状数组比线段树和平衡树好写,且功能强大

题目ACwing244
倒序遍历,每次遍历到的数字表示此元素在剩下的元素中的排名
用树状数组维护那些没有用过的排名
ACcode:

//https://www.acwing.com/problem/content/description/245/
#include <bits/stdc++.h>
#define lowbit(x) x&(-x)
#define N 200010
using namespace std;
typedef long long ll;
void setio(string);

int c[N],a[N],n,m,ans[N];
inline int pre(int x) {//sum 1~x
	int res=0;
	while(x>0) {
		res+=c[x];
		x-=lowbit(x);
	}
	return res;
}
inline int add(int x,int y) {//x的位置+=y 
	while(x<=n) {
		c[x]+=y;
		x+=lowbit(x);
	}
}
int main() {
	setio("");
	cin>>n;
	add(1,1);
	for(int i=2; i<=n; i++) {
		cin>>a[i];
		add(i,1);
	}
	for(int i=n; i>=1; i--) {
		int l=1,r=n;
		while(l<r) { //二分找点
			int mid=l+r>>1;
			if (pre(mid)<a[i]+1)//查询第a[i]+1个1在什么位置,这个位置号就是奶牛的高度
				l=mid+1;
			else
				r=mid;
		}
		ans[i]=r;
		add(r,-1);//我们已经选择了
	}
	for(int i=1; i<=n; i++) //倒序扫描,正序输出
		cout<<ans[i]<<endl;
	return 0;
}
void setio(string name) {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	if(name!="") {
		freopen((name+".in").c_str(),"r",stdin);
		freopen((name+".out").c_str(),"w",stdout);
	}
}

树状数组奆

原文:https://www.cnblogs.com/zhangshaojia/p/15005905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!