题目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