天天看点

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;
}