Minimum Inversion Number(归并排序)

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


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
 题解;题意就是每次把序列的第一个元素放到最后,求最小逆序数;建设当前值为x则,每次逆序数减小x,增加N-1-x;因为x比x个数大,比N-1-X个数小;
代码:
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define MIN(x,y)(x<y?x:y)
 4 const int MAXN=5010;
 5 int a[MAXN],b[MAXN],anser,c[MAXN];
 6 void mergesort(int l,int r,int mid){
 7     int i=l,j=mid+1,k=l;
 8     while(i<=mid&&j<=r){
 9         if(a[i]<=a[j])b[k++]=a[i++];
10         else{
11             anser+=j-k;
12             b[k++]=a[j++];
13         }
14     }
15     while(i<=mid)b[k++]=a[i++];
16     while(j<=r)b[k++]=a[j++];
17     for(i=l;i<=r;i++)a[i]=b[i];
18 }
19 void merge(int l,int r){
20     if(l<r){
21         int mid=(l+r)>>1;
22         merge(l,mid);
23         merge(mid+1,r);
24         mergesort(l,r,mid);
25     }
26 }
27 int main(){
28     int N;
29     while(~scanf("%d",&N)){
30         for(int i=0;i<N;i++)scanf("%d",a+i),c[i]=a[i];
31         anser=0;
32         merge(0,N-1);
33         int temp=anser;
34         //printf("%d\n",anser);
35         for(int i=0;i<N;i++){
36             temp=temp+(N-1-2*c[i]);
37             //printf("%d %d\n",c[i],temp);
38             anser=MIN(anser,temp);
39         }
40         printf("%d\n",anser);
41     }
42     return 0;
43 }
44 //n-a-1-(a) N-2*a+1;

 

posted @ 2015-09-16 20:44  handsomecui  阅读(648)  评论(0编辑  收藏  举报