Minimum Inversion Number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12107 Accepted Submission(s): 7388
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
Sample Output
16
昨天做了几道逆序数的题,全用的树状数组解决的。晚上睡觉的时候发现,树状数组求逆序数,还是有很多麻烦的问题的,1,当序列的的离散程度比较大的大时候,,直接用树状数组,,会MLE,需要离散化序列,虽然不是太难,可模块一多,难免会出现一些比较隐晦的bug,在比赛的时候最忌讳这个了。
2,当序列中有负数的时候,,可能我们就得重新选定坐标原点了,这个原点的坐标得根据数据的范围来选,如果题目说明的不清楚的时候,,就很坑了。
所以我决定再复习一下归并求逆序数,毕竟这个没什么限制,虽然速度不太怎么满意,但好在实用性比较强。
这道题就是给定一个序列,
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)
然后把最小的输出来。
没什么好说的,直接模板,
下面是代码:
#include <stdio.h>
#define MAX 10000
#define INF 100000000
int b[MAX];
int merge(int a[] , int start , int mid , int end)
{
int i = start , j = mid+1 , k = start , count = 0;
while(i<=mid && j<=end)
{
if(a[i]<=a[j])
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
count += mid-i+1;
}
}
while(i<=mid)
{
b[k++] = a[i++] ;
}
while(j<=end)
{
b[k++] = a[j++] ;
}
for(i = start ; i <= end ; ++i)
{
a[i] = b[i] ;
}
return count ;
}
int mergeSort(int a[],int start , int end)
{
int sum = 0 ;
if(start == end)
{
return 0;
}
int mid = (start+end)>>1 ;
sum +=mergeSort(a,start,mid) ;
sum +=mergeSort(a,mid+1,end) ;
sum +=merge(a,start,mid,end) ;
return sum ;
}
int min(int a , int b)
{
return a>b?b:a ;
}
int main()
{
int n ;
while(~scanf("%d",&n))
{
int a[MAX],temp[MAX];
for(int i = 0 ; i < n ; ++i)
{
scanf("%d",&a[i]);
temp[i] = a[i] ;
}
int sum = INF ,ans;
sum = mergeSort(a,0,n-1) ;
ans = sum ;
for(int i = 0 ; i < n-1 ; ++i)
{
sum += -temp[i]+ n-temp[i]-1;
ans = min(sum,ans) ;
}
printf("%d\n",ans) ;
}
return 0;
}
AC状态: