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
题意:
给出一个排列,每次可以将开头的一个数移到最后面,最后变成an a1 a2 a3… an-1。求移动过程中的最小逆序数,原序列逆序数也算一种。
思路:
移动过程的逆序数变化其实是确定的。
假设开头是x,那么后面的序列大于x的数y = n - x,小于x的数z = x - 1。
逆序数变化为y - x = n - 2 * x + 1。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int maxn = 5e3 + 7;
int n;
int a[maxn],c[maxn];
void add(int x,int v)
{
while(x <= n)
{
c[x] += v;
x += x & (-x);
}
}
int query(int x)
{
int res = 0;
while(x)
{
res += c[x];
x -= x & (-x);
}
return res;
}
int main()
{
while(~scanf("%d",&n))
{
memset(c,0,sizeof(c));
int ans = 0,tmp = 0;
for(int i = 1;i <= n;i++)
{
scanf("%d",&a[i]);
a[i]++;
tmp += query(n) - query(a[i]);
add(a[i],1);
}
ans = tmp;
for(int i = 1;i < n;i++)
{
tmp = tmp + n - 2 * a[i] + 1;
ans = min(ans,tmp);
}
printf("%d\n",ans);
}
return 0;
}