标签:
归并排序计算逆序数
#include <iostream> #include <cstdio> using namespace std; #define maxn 1000005 int a[maxn], temp[maxn]; long long ans; void MergeSort(int a[], int l, int mid, int r) { int k=0; int i = l, n = mid, j = mid, m = r; while ( i<n && j<m ) { if (a[i] <= a[j]) { temp[k++] = a[i++]; } else { ans += n-i; temp[k++] = a[j++]; } } while (i<n) temp[k++] = a[i++]; while (j<m) temp[k++] = a[j++]; for (int t = 0; t<k; ++t) a[l+t] = temp[t]; } void Sort(int a[], int l, int r) { if (r-l<=1) return ; int mid = (l+r)>>1; Sort(a, l, mid); Sort(a, mid, r); MergeSort(a, l, mid, r); } int main() { int n; while (~scanf("%d", &n)) { if(n == 0) return 0; for (int i=0; i < n; ++i) scanf("%d", &a[i]); ans = 0; Sort(a, 0, n); printf("%lld\n", ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/jifahu/p/5449512.html