天天看點

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
 有一個n個整數的排列,這n個整數就是0,1,2,3...n-1這n個數( 但不一定按這個順序給出)。現在先計算一下初始排列的逆序數,然後把第一個元素a1放到an後面去,形成新排列a2 a3 a4...an a1,然後再求這個排列的逆序數。繼續執行類似操作(一共要執行n-1次)直到産生排列an a1 a2...an-1為止。計算上述所有排列的逆序數,輸出最小逆序數。
  假設樹狀數組為c[i],它所要加速的數組為a[i],輸入的為b[i],我們先隻考慮a[i]和b[i],樸素的想法是每輸入一個b[i],就判斷從0<=j<=i-1,如果b[j]>b[i],那麼ans++(當然,這道題完全可以這麼水過去)。那麼現在,每輸入一個b[i],我就用a[b[i]+1]++去标記總共輸入多少次了(因為輸入的資料是0~n-1,是以輸入的b[i]就相當于a[i]的下标i,而且有0,樹狀數組無法對下标為0進行操作,是以要a[b[i]+1]),那麼現在很明顯了,對于一個b[i],要想查詢它前面有多少大于它的,隻需将a[b[i]+1]到a[n]加起來,也就是求一段數組的和,那麼樹狀數組就上場加速了。

AC代碼:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;

int c[5005], n, a[5005];
int lowbit(int t)
{
    return t&(-t);
}
int getsum(int pos)
{
    int ans = 0;
    while (pos > 0)
    {
        ans += c[pos];
        pos -= lowbit(pos);
    }
    return ans;
}
void update(int pos, int val)
{
    while (pos <= n)
    {
        c[pos] += val;
        pos += lowbit(pos);
    }
}
int main(void)
{
    while(~scanf("%d", &n))
    {
        int ans = 0;
        memset(c, 0, sizeof(c));
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            ans +=getsum(n)- getsum(a[i] + 1);//編号最大是n-1,加一後是n
            update(a[i] + 1, 1);
        }
        int cnt = ans;
        //printf("%d\n", ans);
        for (int i = 0; i < n; i++)
        {
            cnt = cnt + n - 1 - 2 * a[i];
            ans = min(ans, cnt);
        }
        printf("%d\n", ans);
    }
    return 0;
}