您的位置:首页 > 其它

Minimum Inversion Number(归并排序)

2015-09-16 20:44 309 查看

Minimum Inversion Number

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14952 Accepted Submission(s): 9140


[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each case, output the minimum inversion number on a single line.

[align=left]Sample Input[/align]

10 1 3 6 9 0 8 5 7 4 2

[align=left]Sample Output[/align]

16

题解;题意就是每次把序列的第一个元素放到最后,求最小逆序数;建设当前值为x则,每次逆序数减小x,增加N-1-x;因为x比x个数大,比N-1-X个数小;
代码:

#include<stdio.h>
#include<string.h>
#define MIN(x,y)(x<y?x:y)
const int MAXN=5010;
int a[MAXN],b[MAXN],anser,c[MAXN];
void mergesort(int l,int r,int mid){
int i=l,j=mid+1,k=l;
while(i<=mid&&j<=r){
if(a[i]<=a[j])b[k++]=a[i++];
else{
anser+=j-k;
b[k++]=a[j++];
}
}
while(i<=mid)b[k++]=a[i++];
while(j<=r)b[k++]=a[j++];
for(i=l;i<=r;i++)a[i]=b[i];
}
void merge(int l,int r){
if(l<r){
int mid=(l+r)>>1;
merge(l,mid);
merge(mid+1,r);
mergesort(l,r,mid);
}
}
int main(){
int N;
while(~scanf("%d",&N)){
for(int i=0;i<N;i++)scanf("%d",a+i),c[i]=a[i];
anser=0;
merge(0,N-1);
int temp=anser;
//printf("%d\n",anser);
for(int i=0;i<N;i++){
temp=temp+(N-1-2*c[i]);
//printf("%d %d\n",c[i],temp);
anser=MIN(anser,temp);
}
printf("%d\n",anser);
}
return 0;
}
//n-a-1-(a) N-2*a+1;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: