HDU 5592 (线段树)

ZYB's Premutation

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


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
 


题意是构造一个1-n的排列,使得前i到前i个数为止的逆序对个数等于a[i].

从后往前确定每一位数字,a[i]-a[i-1]表示的就是第i个数产生的逆序对数,也就是第i个数之前有这么多比他大的数,所以只需要在剩下的数字中找到第a[i]-a[i-1]+1大的数就好了.用线段树维护很方便.

#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
#define maxn 51111
#define pl c<<1
#define pr (c<<1)|1
#define lson tree[c].l,tree[c].mid,c<<1
#define rson tree[c].mid+1,tree[c].r,(c<<1)|1

struct node {
    int l, r, mid;
    int sum; //这个区间没有用过的数字的个数
}tree[maxn<<4];
int n;
int a[maxn], ans[maxn];

void build_tree (int l, int r, int c) {
    tree[c].l = l, tree[c].r = r, tree[c].mid = (r+l)>>1;
    tree[c].sum = r-l+1;
    if (l == r) {
        return ;
    }
    build_tree (lson);
    build_tree (rson);
}

int get (int l, int r, int c, int k) { //从后往前第k大的
    if (l == r) {
        tree[c].sum = 0;
        return l;
    }
    int ans;
    if (tree[pr].sum >= k)
        ans = get (rson, k);
    else
        ans = get (lson, k-tree[pr].sum);
    tree[c].sum = tree[pl].sum + tree[pr].sum;
    return ans;
}

void solve () {
    build_tree (1, n, 1);
    for (int i = n; i >= 1; i--) {
        int x = a[i]-a[i-1];
        int id = get (1, n, 1, x+1);
        ans[i] = id;
    }
    for (int i = 1; i < n; i++)
        printf ("%d ", ans[i]);
    printf ("%d\n", ans[n]);
}

int main () {
    //freopen ("in", "r", stdin);
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%d", &n);
        a[0] = 0;
        for (int i = 1; i <= n; i++) {
            scanf ("%d", &a[i]);
        }
        solve ();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值