归并排序模版:
1 #include<stdio.h> 2 3 long long int ans, n; 4 long long int a[501000], b[501000]; 5 6 void mergesort(int start, int end) 7 { 8 if(start < end) 9 { 10 int i, j, mid = (start+end)>>1; 11 mergesort(start, mid); 12 mergesort(mid+1, end); 13 int t = start; 14 j = mid+1; i = start; 15 while(i<=mid && j <= end) 16 { 17 if(a[i] <= a[j]) 18 b[t++] = a[i++]; 19 else 20 { 21 b[t++] = a[j++]; 22 ans += mid-i+1; 23 } 24 } 25 while(i<=mid) 26 b[t++] = a[i++]; 27 while(j<=end) 28 b[t++] = a[j++]; 29 for(int k = start; k <= end; k ++) 30 a[k] = b[k]; 31 } 32 } 33 34 int main() 35 { 36 while(scanf("%lld",&n)) 37 { 38 ans = 0; 39 if(n == 0) break; 40 for(int i = 0; i < n; i ++) 41 scanf("%lld",&a[i]); 42 mergesort(0,n-1); 43 printf("%lld\n",ans); 44 } 45 return 0; 46 }