Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6937 Accepted Submission(s): 4233
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
Recommend Ignatius.L
題意:将一個n個元素的排列,可以将第一個元素放到最後一個元素後面得出n個排列,求這n個排列的最少逆序數對 題解:用樹狀數組,按順序插入,求出排列的逆序數對temp,模拟将第一個元素移走,那麼逆序數對就減少sum(a-1)個,将這個數放到最後一位,逆序數對就增加(n-1)-sum(a-1)對,是以每次轉變就有temp=temp+n-1-2*sum(a【i】-1),依次可以算出最少的逆序數對值
#include<stdio.h>
#include<string.h>
#define MAX 1000005
int tree[MAX],a[5005];
int low_bit(int x)
{
return x&(-x);
}
void add(int x,int y)
{
while(x<MAX)
{
tree[x]+=y;
x+=low_bit(x);
}
}
int ques(int x)
{
int temp=0;
while(x>0)
{
temp+=tree[x];
x-=low_bit(x);
}
return temp;
}
int main()
{
int temp,sum,n,i;
while(scanf("%d",&n)>0)
{
memset(tree,0,sizeof(tree));
for(i=1;i<=n;i++) scanf("%d",a+i);
for(temp=0,i=n;i>=1;i--)
{
a[i]++;
temp=temp+ques(a[i]-1);
add(a[i],1);
}
sum=temp;
for(i=1;i<n;i++)
{
temp=temp+n-1-2*ques(a[i]-1);
if(temp<sum) sum=temp;
}
printf("%d\n",sum);
}
return 0;
}