1. 程式人生 > 實用技巧 >4.逆序對的數量

4.逆序對的數量

注意資料範圍,n=100000,從大到小時,逆序對數量最多。

約為5 * 10 ^ 9。超過了int的最大範圍,所以需要用longlong來存。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 100010;
 4 int a[N];
 5 int tmp[N];
 6 typedef long long ll;
 7 ll merge_sort(int l, int r) {
 8     if (l >= r) {
 9         return 0;
10     }
11     int mid = (l + r) >> 1
; 12 ll ans = merge_sort(l, mid) + merge_sort(mid + 1, r); 13 int k = 0, i = l, j = mid + 1; 14 while (i <= mid && j <= r) { 15 if (a[i] <= a[j]) { 16 tmp[k++] = a[i++]; 17 } else { 18 tmp[k++] = a[j++]; 19 ans += mid - i + 1
; 20 } 21 } 22 while (i <= mid) { 23 tmp[k++] = a[i++]; 24 } 25 while (j <= r) { 26 tmp[k++] = a[j++]; 27 } 28 for (int i = l, j = 0; i <= r; i++, j++) { 29 a[i] = tmp[j]; 30 } 31 return ans; 32 } 33 int main () { 34 int n; 35
cin >> n; 36 for (int i = 0; i < n; i++) { 37 cin >> a[i]; 38 } 39 cout << merge_sort(0, n - 1) << endl; 40 return 0; 41 }