hdu 5592 ZYB's Premutation

权值线段树求第k小。

题意给n个数所有前缀中的逆序对数,构造出原序列。

第i个前缀减去第i-1个前缀就是第i个值插入序列后增加的逆序对,也就是说前面有这么多数比当前数大。那么i减去这个数代表当前数是前i个数的区间第k小。

维护一个权值线段树,初始节点权值分别为1...n。

从后向前考虑,每遇到一个数就是求当前权值线段树的区间第k小,再把这个数从线段树中删除即可。

 

#include <bits/stdc++.h>
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define up rt,rt<<1,rt<<1|1
using namespace std;
const int M = 5e4+7;
int _,n,pos,a[M],ans[M];
struct Tree
{
    int num,val;
}tree[M<<2];
void pushup(int rt,int l,int r){
    tree[rt].num=tree[l].num+tree[r].num;
}
void build(int l,int r,int rt){
    tree[rt].num=0;
    if(l==r){
        tree[rt].num=1;tree[rt].val=l;return ;
    }
    int mid=(l+r)>>1;
    build(lson);
    build(rson);
    pushup(up);
}
void update(int l,int r,int rt){
    if(l==r){
        tree[rt].num--;return ;
    }
    int mid=(l+r)>>1;
    if(pos<=mid) update(lson);
    else update(rson);
    pushup(up);
}
int query(int l,int r,int rt,int k){
    if(l==r){
        return tree[rt].val;
    }
    int mid=(l+r)>>1;
    if(tree[rt<<1].num>=k) return query(lson,k);
    else return query(rson,k-tree[rt<<1].num);
}
int main(){
    scanf("%d",&_);
    while(_--){
        scanf("%d",&n);
        build(1,n,1);
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);a[0]=0;
        for(int i=n;i>=1;i--){
            int k=i-(a[i]-a[i-1]);
            ans[i]=query(1,n,1,k);pos=ans[i];
            update(1,n,1);
        }
        for(int i=1;i<=n;i++) printf("%d%c",ans[i],i==n?'\n':' ');
    }
    return 0;
}
View Code

 

转载于:https://www.cnblogs.com/LMissher/p/9558863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值