标签:
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 44489 | Accepted: 16176 |
Description
Input
Output
Sample Input
5 9 1 0 5 4 3 1 2 3 0
Sample Output
6 0
题目大意就是让你计算一个冒泡排序中,需要交换的次数。
以为数据量较大,所以我们这里用到了Merge Sort :
1 #include<stdio.h> 2 #include<string.h> 3 int temp[500005] ; 4 int a[500005] ; 5 __int64 number ; 6 void MergeSort( int a[] , int fir , int end ) 7 { 8 int len = end - fir ; 9 if( len <= 1 ) 10 return ; 11 int mid = fir + len/2 ; 12 MergeSort( a , fir , mid ) ; 13 MergeSort( a , mid , end ) ; 14 int p1 = fir , p2 = mid ; 15 for( int i = fir ; i < end ; i++ ) 16 { 17 if( p1 == mid ) 18 { 19 temp[i] = a[p2++] ; 20 } 21 else if( p2 == end ) 22 { 23 temp[i] = a[p1++] ; 24 } 25 else 26 { 27 if( a[p1] >= a[p2] ) 28 { 29 temp[i] = a[p2++] ; 30 number += mid - p1 ;//在Merge Sort 排序中仅仅多加了这句话 31 } 32 else 33 { 34 temp[i] = a[p1++] ; 35 } 36 } 37 } 38 39 for(int i = fir ; i < end ; i++ ) 40 { 41 a[i] = temp[i] ; 42 } 43 } 44 int main() 45 { 46 // freopen("a.txt" ,"r" , stdin ); 47 int n ; 48 while( scanf("%d" , &n ) != EOF ) 49 { 50 if( n == 0 ) break; 51 number = 0 ; 52 for(int i = 0 ; i < n ; i++ ) 53 scanf("%d" , &a[i] ) ; 54 MergeSort( a , 0 , n ) ; 55 56 printf("%I64d\n" , number ); 57 } 58 return 0 ; 59 }
标签:
原文地址:http://www.cnblogs.com/get-an-AC-everyday/p/4266074.html