HDU 5592 线段树

HDU 5592
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5592
题意:
一串1-n的排列。(n <= 5000)
定义a[i]为前i个数的逆序对数,然后要还原这个排列。
思路:
现场的时候有思路,但是线段树不会敲就放弃了。
简单说一下思路,从后往前遍历,由a[i] - a[i - 1]知道当前这个位置放的是剩下的数中第几大的数。

着重说一下线段树怎么写。
设点数n = 5.
一开始把n个数置为1
1 1 1 1 1
线段树里面存的是前缀和
1 2 3 4 5
然后每次根据前缀和查询出刚好为这个值的位置,类似二叉查找树。
if(u > query(o * 2) return query(o * 2 + 1)
Else return query(o * 2)
更新的时候把这个需要更新的叶子节点置为0,然后向上更新前缀和。

看似简单,实则用的很活。平时查找和更新都是要找结点的标记来查找,现在通过值来查找标记。学到了~
源码:

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;
const int MAXN = 50000 + 5;
#define LL long long
LL a[MAXN];
int ans[MAXN];
struct Tree
{
    int l, r;
    int val;
}tree[MAXN * 4];
void push_up(int o)
{
    tree[o].val = tree[o * 2 + 1].val + tree[o * 2].val;
}
void build(int l, int r, int o)
{
    tree[o].l = l, tree[o].r = r, tree[o].val = 0;
    if(l == r){
        tree[o].val = 1;
        return;
    }
    int mid = (l + r) / 2;
    build(l, mid, o * 2);
    build(mid + 1, r, o * 2 + 1);
    push_up(o);
}
void update(int u, int val, int o)
{
//    printf("u = %d, val = %d, tree[o].l = %d, tree[o].r = %d\n", u, val, tree[o].l, tree[o].r);
    if(tree[o].l == tree[o].r){
        tree[o].val += val;
        return;
    }
    int mid = (tree[o].l + tree[o].r) >> 1;
    if(u <= mid)    update(u, val, o * 2);
    else    update(u, val, o * 2 + 1);
    push_up(o);
}
int query(int u, int o)
{
    if(tree[o].l == tree[o].r)  return tree[o].l;
    if(u > tree[o * 2].val)   return query(u - tree[o * 2].val, o * 2 + 1);
    else    return query(u, o * 2);
}
int main()
{
    int T;
    scanf("%d", &T);
    while(T--){
        int n;
        scanf("%d", &n);
        build(1, n, 1);
//        printf("tree[1].l = %d, tree[1].r = %d\n", tree[1].l, tree[1].r);
        for(int i = 1 ; i <= n ; i++)   scanf("%I64d", &a[i]);
        a[0] = 0;
        for(int i = n ; i >= 1 ; i--){
            int pian = i- (a[i] - a[i - 1]);
//            printf("pian = %d\n", pian);
            ans[i] = query(pian, 1);
//            printf("ans[i] = %d\n", ans[i]);
            update(ans[i], -1, 1);
        }
        for(int i = 1 ; i <= n ; i++){
            printf("%d", ans[i]);
            if(i == n)  printf("\n");
            else    printf(" ");
        }
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值