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;
相关文章推荐
- Javascript 时间相关随记
- 跨域加载脚本或页面获取内容
- 一个关于CSS选择器“优先级”的新问题
- 数据解析1:XML解析(1)
- 机器学习十大经典算法
- uva 12096
- 第三周实践项目1-顺序表的基本运算总结
- Android 无法获取正在运行的程序
- [LeetCode] Gray Code
- 判断闰年
- Android之自定义View以及画一个时钟
- 初识Linux
- 四、集合与泛型、委托与事件-----《大话设计模式》
- 决策树代码
- Linux内核学习(二)---Linux中的进程、线程和轻量级进程
- HDU - 2444 The Accomodation of Students(二分图判断+最大匹配)
- "Class not found: javac1.8"问题总结
- hdu 1060 Leftmost Digit
- 基因检测如何让癌症变的可预防?
- libsvm-2.84在MATLAB中使用遇到的刻骨铭心的error