HDU 5592 线段树根据逆序数求原序列

ZYB's Premutation

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 758    Accepted Submission(s): 359


Problem Description
ZYB has a premutation P ,but he only remeber the reverse log of each prefix of the premutation,now he ask you to
restore the premutation.

Pair (i,j)(i<j) is considered as a reverse log if Ai>Aj is matched.
 

Input
In the first line there is the number of testcases T.

For each teatcase:

In the first line there is one number N .

In the next line there are N numbers Ai ,describe the number of the reverse logs of each prefix,

The input is correct.

1T5 , 1N50000
 

Output
For each testcase,print the ans.
 

Sample Input
  
  
1 3 0 1 2
 

Sample Output
  
  
3 1 2
 

Source
 
题意:
输入 T,T组数据,n个数,每个数表示 i 之前存在多少个 前数大于后数 的个数。
 a[i] 表示 a[i]与a[i]之前的逆序数的个数和 。

fi是第i个前缀的逆序对数,pi是第i个位置上的数,则fi-f(i-1)是i前面比pi大的数的个数.我们考虑倒着做,当我们处理完i后面的数,第i个数就是剩下的数中第fi-f(i-1)大的数,用线段树和树状数组可以求出当前第k个是1的位置,复杂度O(n*log(n)).


树的节点保存三个值:左端点a,右端点b,该区间剩下的数字的个数sum。
(因为左右区间值均等)
查询第k大的时候,当k大于右子节点的sum,则查询左子节点第(k-右子节点的sum)大 ,否则查询右子节点,
当左端点等于右端点时返回(此时找到了)


#include<bits/stdc++.h>
//#define mid (l+r)>>1
//#define Mid (L+R)>>1
//#define lson l,mid,ind<<1
//#define rson mid+1,r,ind<<1|1
using namespace std;
int Tr[60000*4],a[60000],b[60000],c[60000];
int Updata(int ind)
{
    Tr[ind]=Tr[ind<<1]+Tr[ind<<1|1];
}
int Build(int l,int r,int ind)
{
    if(l==r)
    {
        Tr[ind]=1;
        return 0;
    }
    int mid=(l+r)>>1;
    Build(l,mid,ind<<1);
    Build(mid+1,r,ind<<1|1);
    Updata(ind);
}
int Query(int l,int r,int ind,int x)
{
    Tr[ind]--;
    if(l==r)
        return l;
    int mid=(l+r)>>1;
    if(x>Tr[ind<<1|1])                  //大于右区间中存的个数,说明在左区间中
    Query(l,mid,ind<<1,x-Tr[ind<<1|1]);  //因为是在左区间中。所以,该数应该是在左区间中是第x-Tr[ind<<1|1]大的数。
    else
    Query(mid+1,r,ind<<1|1,x);    //小于时说明是在右区间中的第x大。
}
int main()
{
    int T,n;
    while(~scanf("%d",&T))
    {
        while(T--)
        {
            scanf("%d",&n);
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
            for(int i=1;i<n;i++)
                b[i]=a[i]-a[i-1];
            b[0]=0;
            Build(1,n,1);
            for(int i=n-1;i>=0;i--)
            {
                c[i]=Query(1,n,1,b[i]+1);
            }
            for(int i=0;i<n;i++)
            {
                if(i!=0)
                    printf(" ");
                printf("%d",c[i]);
            }
            printf("\n");
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值