poj 2299 Ultra-QuickSort 归并排序 /* 题解:逆序数,仅此而已。。 PS: 水题,还是写了半个小时。 */ #include <iostream> #include <algorithm> using namespace std; const int inf = 1<<28; int n,m; int a[500010],temp[500010],ans; void Merge_Sort(int a[],int l,int r) { if (l>=r) return ; int mid = (l+r)>>1; Merge_Sort(a,l,mid); Merge_Sort(a,mid+1,r); int i,j,k; for (k=l,i=l,j=mid+1;i<=mid && j<=r;k++) { if (a[i]<=a[j]) temp[k]=a[i++]; else { ans+=mid-i+1; temp[k]=a[j++]; } } while (i<=mid) temp[k++]=a[i++]; while (j<=r) temp[k++]=a[j++]; for (i=l;i<=r;i++) a[i]=temp[i]; } int main() { while (scanf("%d",&n) && n) { for (int i=0;i<n;i++) scanf("%d",&a[i]); ans=0; Merge_Sort(a,0,n-1); printf("%d/n",ans); } system("pause"); return 0; }