Title Link: http://poj.org/problem?id=2299
Test instructions is to ask the array in order from small to large, at a time can only exchange adjacent two number, for at least a few exchanges
is to find the reverse number by merging sort
#include <stdio.h>#include<string.h>#include<algorithm>#defineN 501000using namespacestd;intA[n], B[n];__int64 cnt;voidMerge (intRintMidintl) { inti = r, j = mid+1, k =0; while(I<=mid && j<=l) {if(A[i] >A[j]) {B[k+ +] = a[j++]; CNT+ = mid-i+1;///indicating that the subscript from I to mid values are larger than a[j], so the number of reverse order to +mid-i+1; } Else if(A[i] <A[j]) {B[k+ +] = a[i++]; } Else{b[k+ +] = a[i++]; J++; } } while(i<=mid) B[k+ +] = a[i++]; while(j<=l) b[k+ +] = a[j++]; for(i=0; i<k; i++)///brushes an ordered array of temporary elements back into the sorted array A,A[I+R] =b[i];}voidMergeSort (intRintl) { intMid = (r+l)/2; if(R <l) {mergesort (R, mid);///sort the first half of the sectionMergeSort (Mid +1, l);///sort the second half of the sectionMerge (R, Mid, L);///two parts before and after merging }}intMain () {intN; while(SCANF ("%d", &N), N) {cnt=0; for(intI=0; i<n; i++) scanf ("%d", &A[i]); MergeSort (0, N-1); printf ("%i64d\n", CNT); } return 0;}
Ultra-quicksort---poj2299 (merge sort)