题目链接:http://poj.org/problem?id=2182
题目大意:有编号为1到n的n头牛按照某一编号排列,现在他们的顺序打乱了,FJ只记得每头牛前面有多少个牛的编号比它大,让还原出n头牛的原始队列。
分析:对于最后一头牛来说,他前面编号比他大的牛的数目+1,就是它本身的编号,然后我们把它的编号移除,这样,对于倒数第二只牛,我们仍然可以这样做来得到它的编号,至于实现上,我们用线段是来纪录每个区间内的编号的数目len,每移除一头牛,我们将他所在的区间的len值减1即可。
实现代码如下;
#include <cstdio>
using namespace std;
const int M=8005;
struct segment
{
int l,r;
int len; //纪录区间内有多少个元素
int mid()
{
return (l+r)>>1;
}
}tree[M<<2];
void build(int rt,int l,int r)
{
tree[rt].l=l;
tree[rt].r=r;
tree[rt].len=r-l+1;
if(l==r) return ;
int m=tree[rt].mid();
build(rt<<1,l,m);
build(rt<<1|1,m+1,r);
}
int query(int rt,int v)
{
tree[rt].len--;
if(tree[rt].l==tree[rt].r)
return tree[rt].l;
if(v<=tree[rt<<1].len) return query(rt<<1,v);
if(v>tree[rt<<1].len) return query(rt<<1|1,v-tree[rt<<1].len);
}
int pre[M],ans[M];
int main()
{
int n;
while(scanf("%d",&n)!=-1)
{
build(1,1,n);
pre[1]=0;
for(int i=2;i<=n;i++)
scanf("%d",&pre[i]);
for(int i=n;i>0;i--)
ans[i]=query(1,pre[i]+1);
for(int i=1;i<=n;i++)
printf("%d\n",ans[i]);
}
return 0;
}