HDU1394——线段树——Minimum Inversion Number

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
 
/*
a[i]从0到n-1
先求出原来序列的逆序对
假设先放进一个数a[i],那么就用线段树查找是否在里面有大于a[i]的数如果有就++,update
对于已经求出的逆序对,因为序列所有数字排序之后都是0-n而逆序对所有的情况都在这里面,假设ans为逆序对。b[1]为第一个数对于后面所有数的逆序数,那么如果把这个数放到后面去就少了b[1],多了n-1-b[1],而这个b肯定在1~n-1范围内
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

const int MAX = 50100;
int a[MAX];
int sum[MAX<<2];

void build(int rt, int l, int r)
{
    sum[rt] = 0;
    if(l == r){
        return;
    }
    int mid = (l + r) >> 1;
    build(rt*2, l, mid);
    build(rt*2+1, mid+1, r);
}

void update(int rt, int l, int r, int L)
{
    if(l == r){
        sum[rt]++;
            return;
    }
    int mid = (l + r) >> 1;
    if(L <= mid) update(rt*2, l, mid, L);
    else update(rt*2+1, mid+1, r, L);
    sum[rt] = sum[rt*2] + sum[rt*2+1];
}

int query(int rt, int l, int r, int L, int R)
{
    if(L <= l && R >= r) return sum[rt];
    int mid = (l + r) >> 1;
    int ret = 0;
    if(L <= mid) ret += query(rt*2, l, mid, L, R);
    if(R >mid) ret += query(rt*2+1, mid+1, r, L, R);
    sum[rt] = sum[rt*2] + sum[rt*2+1];
    return ret;
}

int main()
{
    int n;
    while(scanf("%d", &n)!=EOF){
        build(1, 0, n-1);
        int ans = 0;
        for(int i = 1; i <= n ;i++){
           scanf("%d", &a[i]);
           ans = ans + query(1, 0, n-1, a[i], n-1);
           update(1, 0, n-1, a[i]);
        }
        int min1 = ans;
        for(int i = 1; i <= n  ; i++){
           ans += n - 2*a[i] - 1;
           min1 = min(min1, ans);
        }
        printf("%d\n", min1);
    }
    return 0;
}

  

posted @ 2015-07-29 16:31  Painting、时光  阅读(167)  评论(0编辑  收藏  举报