http://poj.org/problem?id=2299
1 #include<stdio.h> 2 int a[500005]; 3 long long count; 4 5 void merge(int first,int mid,int last) 6 { 7 int s1,s2,f1,f2,i,k,f[500005]; 8 s1=first; 9 s2=mid+1; 10 f1=mid; 11 f2=last; 12 k=0; 13 while(s1<=f1&&s2<=f2) 14 { 15 if(a[s1]<a[s2]) 16 f[k++]=a[s1++]; 17 else 18 { 19 f[k++]=a[s2++]; 20 count+=mid-s1+1; 21 } 22 } 23 while(s2<=f2) 24 f[k++]=a[s2++]; 25 while(s1<=f1) 26 f[k++]=a[s1++]; 27 for(i=first;i<=last;i++) 28 a[i]=f[i-first]; 29 } 30 31 void mergesort(int start,int end) 32 { 33 int mid=0; 34 if(start==end) 35 return; 36 mid=(start+end)/2; 37 mergesort(start,mid); 38 mergesort(mid+1,end); 39 merge(start,mid,end); 40 } 41 42 int main() 43 { 44 int n,i; 45 while(scanf("%d",&n)&&n) 46 { 47 for(i=0;i<n;i++) 48 scanf("%d",&a[i]); 49 count = 0; 50 mergesort(0,n-1); 51 printf("%lld\n",count); 52 } 53 return 0; 54 }
用时3672MS。有大神用时141MS。求更优题解!