poj2182

题目大意:有n头牛,给出从第二头牛开始每头牛前面有多少头牛编号比自己小。

求牛的编号。

分析:每次最后一头牛的编号为当前可用编号中排在第a[i]+1的数。

-------->线段树 O(nlogn)

维护一个区间内还有多少个数可以用(因为要求可以用的第k个数)。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct node{
int l,r,len;
}tree[32000];
int n;
int a[8010],ans[8010];
void build(int p,int l,int r)
{
   tree[p].l=l;
   tree[p].r=r;
   tree[p].len=r-l+1;
   if (l==r) return ;
   int mid=(l+r) >> 1;
   build(p<<1,l,mid);
   build(p<<1^1,mid+1,r);
}
int ask(int p,int x)//找tree[p].l~tree[p].r中的第x个数
{
    if (tree[p].l==tree[p].r)
    {
        return tree[p].l;
    }
    if (tree[p<<1].len>=x) return ask(p<<1,x);
    if (tree[p<<1].len<x) return ask(p<<1^1,x-tree[p<<1].len);
}
void clean(int p,int x)
{
    if (tree[p].l==tree[p].r)
    {
        tree[p].len=0;
        return ;
    }
    int mid=(tree[p].l+tree[p].r) >> 1;
    if (x<=mid) clean(p<<1,x);
    if (x>mid) clean(p<<1^1,x);
    tree[p].len--;
}
int main()
{
    cin>>n;
    for (int i=2;i<=n;i++)
        cin>>a[i];
    a[1]=0;
    build(1,1,n);
    for (int i=n;i;i--)
    {
        ans[i]=ask(1,a[i]+1);
        clean(1,ans[i]);
    }
    for (int i=1;i<=n;i++)
        cout<<ans[i]<<endl;
    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值