如题:http://poj.org/problem?id=2182
有N个数,从第二个数到第N个数,依次给出这个数前面有几个比他序号小的数,最后输出这些数的序号。
先看最后一个数,它前面有n个数比他序号小,那么它的序号一定是n+1,然后将它删掉,再看最后一个数。查询操作符合线段树的要求。
线段树节点lc,rc,len分别表示的是编号区间lc-rc中当有len个元素在里面。每次查询,len--,如果当前是第x个元素包含在这个节点里面,进入左子树,
否则在右子树中查找x-左子树.len.
#include<iostream>
using namespace std;
#define N 10000
int small[N],ans[N];
struct segment
{
int rc,lc,len;
};
segment s[30000];
void build(int root,int lc,int rc)
{
s[root].lc=lc;
s[root].rc=rc;
s[root].len=rc-lc+1;
if(lc==rc) return;
build(root*2,lc,(lc+rc)/2);
build(root*2+1,(lc+rc)/2+1,rc);
}
int query(int root,int k)
{
s[root].len--;
if(s[root].lc==s[root].rc) return s[root].lc;
else if(k<=s[2*root].len)
return query(root*2,k);
else
return query(root*2+1,k-s[2*root].len);
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=2;i<=n;i++)
scanf("%d",&small[i]);
small[1]=0;
build(1,1,n);
for(i=n;i>=1;i--)
ans[i]=query(1,small[i]+1);
for(i=1;i<=n;i++)
printf("%d\n",ans[i]);
return 0;
}