首页 > 代码库 > hdu 1394 Minimum Inversion Number(线段树之 单点更新求逆序数)

hdu 1394 Minimum Inversion Number(线段树之 单点更新求逆序数)

Minimum Inversion Number

                                                                          Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Problem Description
The inversion number of a given number sequence a1, a2, ..., an is the number of pairs (ai, aj) that satisfy i < j and ai > aj.

For a given sequence of numbers a1, a2, ..., an, if we move the first m >= 0 numbers to the end of the seqence, we will obtain another sequence. There are totally n such sequences as the following:

a1, a2, ..., an-1, an (where m = 0 - the initial seqence)
a2, a3, ..., an, a1 (where m = 1)
a3, a4, ..., an, a1, a2 (where m = 2)
...
an, a1, a2, ..., an-1 (where m = n-1)

You are asked to write a program to find the minimum inversion number out of the above sequences.
 

Input
The input consists of a number of test cases. Each case consists of two lines: the first line contains a positive integer n (n <= 5000); the next line contains a permutation of the n integers from 0 to n-1.
 

Output
For each case, output the minimum inversion number on a single line.
 

Sample Input
10 1 3 6 9 0 8 5 7 4 2
 

Sample Output
16
 
题意:给出一个含有n个数的序列,然后每次都把第一个数放到序列的最后面形成新的序列,求这n个序列中最小的逆序数是多少?

分析:因为数列中每个元素的值都不相同,所以我们只需求出原始序列的逆序数,然后根据这个逆序数递推出其他序列的逆序数。
例如序列 2 0 3 1 4 5 的逆序数是3,把2放到最后边以后,比2小的数(2个)的每个数的逆序数减1,比2大的数(n-a[i]-1个)的逆序数不变,而2的逆序数变为比2大的数的个数(n-a[i]-1)。根据这个结论,我们就可以递推出其他序列的逆序数,进而求出最小值。
求原始序列的逆序数时用线段树来求,对于第i个数,它的逆序数等于已经插入到线段树中的比它大的数的个数。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int N = 5005;
#define lson l, mid, root<<1
#define rson mid+1, r, root<<1|1
int sum[N<<2], a[N];

void Push_Up(int root)
{
    sum[root] = sum[root<<1] + sum[root<<1|1];
}
void build_tree(int l, int r, int root)
{
    sum[root] = 0;
    if(l == r) return;
    int mid = (l + r) >> 1;
    build_tree(lson);
    build_tree(rson);
}
void update(int p, int l, int r, int root)
{
    if(l == r)
    {
        sum[root]++;
        return;
    }
    int mid = (l + r) >> 1;
    if(p <= mid) update(p, lson);
    else update(p, rson);
    Push_Up(root);
}
int Query(int L, int R, int l, int r, int root)
{
    if(L <= l && r <= R)
    {
        return sum[root];
    }
    int mid = (l + r) >> 1;
    int ans = 0;
    if(L <= mid) ans += Query(L, R, lson);
    if(R > mid) ans += Query(L, R, rson);
    return ans;
}

int main()
{
    int n, i;
    while(~scanf("%d",&n))
    {
        build_tree(0, n-1, 1);
        int res = 0;
        for(i = 0; i < n; i++)
        {
            scanf("%d",&a[i]);
            res += Query(a[i], n-1, 0, n-1, 1); //查询已经插入到线段树中的数有多少个数比a[i]大
            update(a[i], 0, n-1, 1); //把这个数插入到线段树中
        }
        int ans = res;
        for(i = 0; i < n; i++)
        {
            res += (n - a[i] - 1) - a[i];
            ans = min(ans, res);
        }
        printf("%d\n", ans);

    }
    return 0;
}