首页 > 代码库 > HDU 1394 Minimum Inversion Number (线段树)

HDU 1394 Minimum Inversion Number (线段树)

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
 

Author
CHEN, Gaoli
 

Source
ZOJ Monthly, January 2003
 


求最小逆序对数,什么事逆序数呢? 这是对于两个数来说的,例如   2   1,   2在1的前面,2却比1大,那么就是一对逆序对数,
题目求将序列头一个依次放到末尾,这么多序列中逆序对数最少的输出来


首先数据太大,应该用线段树,线段树里面存储的是le  到 ri 的数的数量,例如输入  3,我们就要查询  0到3有多少个已经存在的数
,废话不多说了,直接看代码吧


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
using namespace std;
#define N 5005

int a[N];

struct stud{
int le,ri;
int va;
}f[N*4];


void build(int pos,int le,int ri)
{
    f[pos].le=le;
    f[pos].ri=ri;
    f[pos].va=0;
    if(le==ri)  return ;

    int mid=MID(le,ri);

    build(L(pos),le,mid);
    build(R(pos),mid+1,ri);
}

void update(int pos,int le)
{
    f[pos].va++;

    if(f[pos].le==le&&f[pos].ri==le)
        return ;

    int mid=MID(f[pos].le,f[pos].ri);

    if(mid>=le)
        update(L(pos),le);
    else
        update(R(pos),le);
}

int query(int pos,int le,int ri)
{
    if(f[pos].le>=le&&f[pos].ri<=ri)
        return f[pos].va;

    int mid=MID(f[pos].le,f[pos].ri);

    if(mid>=ri)
        return query(L(pos),le,ri);
    else
        if(mid<le)
        return query(R(pos),le,ri);

    return query(L(pos),le,mid)+query(R(pos),mid+1,ri);
}


int main()
{
    int n,m,i;
    while(~scanf("%d",&n))
    {
        int ans=0;
        build(1,0,n);

        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            ans+=query(1,a[i],n-1);
            update(1,a[i]);
        }

        int temp=ans;

        for(i=0;i<n;i++)
        {
            temp=temp-a[i]+n-a[i]-1;

            if(temp<ans)
                ans=temp;
        }

        printf("%d\n",ans);
    }
    return 0;
}







HDU 1394 Minimum Inversion Number (线段树)