HUST 1347 Reverse Number(归并排序)
Reverse Number
Time Limit: 1 Sec Memory Limit: 128 MBSubmissions: 357 Solved: 66
Description
Given a non-negative integer sequence A with length N, you can exchange two adjacent numbers each time. After K exchanging operations, what’s the minimum reverse number the sequence can achieve?
The reverse number of a sequence is the number of pairs (i, j) such that
i < j and Ai > Aj
Input
There are multiple cases.
For each case, first line contains two numbers: N, K
2<=N<=100000, 0 <= K < 2^60
Second line contains N non-negative numbers, each of which not greater than 2^30
Output
Minimum reverse number you can get after K exchanging operations.
Sample Input
3 1 3 2 1 5 2 5 1 4 3 2
Sample Output
Case #1: 2 Case #2: 5
题目大意:每一次只能交换相邻的两个数字,问经过k次交换以后能够得到的最短的非递增序列
传说中的归并排序
View Code
1 #include <stdio.h> 2 #include <string.h> 3 #include <string.h> 4 int a[110000],c[110000]; 5 int n; 6 long long cnt,k; 7 void mergesort(int l,int r) 8 { 9 int mid,i,j,tmp,q; 10 if (r>l+1) 11 { 12 mid=(l+r)/2; 13 mergesort(l,mid-1); 14 mergesort(mid,r); 15 tmp=l; 16 i=l;j=mid; 17 while (i<mid&&j<=r) 18 { 19 if (a[i]>a[j]) 20 { 21 c[tmp++]=a[j++]; 22 cnt+=mid-i; 23 } 24 else c[tmp++]=a[i++]; 25 } 26 if (j<=r) 27 { 28 for ( ;j<=r;++j) 29 c[tmp++]=a[j]; 30 } 31 else 32 { 33 for (;i<mid;++i) c[tmp++]=a[i]; 34 } 35 for (i=l;i<=r;++i) 36 a[i]=c[i]; 37 } 38 else if (r-l==1&&a[r]<a[l]) {cnt++;q=a[r];a[r]=a[l];a[l]=q;} 39 return; 40 } 41 int main() 42 { 43 bool flag; 44 int i,j,l,m,q,w,e,r; 45 r=0; 46 while (scanf("%d%lld",&n,&k)!=EOF) 47 { 48 r++; 49 cnt=0; 50 for (i=1;i<=n;i++) 51 scanf("%d",&a[i]); 52 mergesort(1,n); 53 cnt=cnt-k; 54 flag=false; 55 for (i=1;i<=n-1;i++) 56 if (a[i]==a[i+1]) flag=true; 57 if (cnt<0) 58 { 59 if((-cnt)%2==0||flag)cnt=0;else cnt=1; 60 } 61 printf("Case #%d: %lld\n",r,cnt); 62 } 63 return 0; 64 }
把每一件简单的事情做好,就是不简单;把每一件平凡的事情做好,就是不平凡!相信自己,创造奇迹~~