1. 程式人生 > >【模板】歸併排序求逆序對

【模板】歸併排序求逆序對

歸併排序求逆序對

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 
 6 typedef long long LL;
 7 const int MAX_N = (int)5e5 + 10;
 8 
 9 int n;
10 LL a[MAX_N], tmpA[MAX_N], cnt = 0;
11 void merge_sort(int l, int r, LL *A) {
12     if
(l >= r) return; 13 14 int mid = (l + r) >> 1; 15 merge_sort(l, mid , A); 16 merge_sort(mid + 1, r, A); 17 18 int sl = l, sr = mid + 1, tmp = 0; 19 while (sl <= mid && sr <= r) { 20 if (A[sl] <= A[sr]) tmpA[tmp++] = A[sl++]; 21 else
tmpA[tmp++] = A[sr++], cnt += mid - sl + 1; 22 } 23 while (sl <= mid) tmpA[tmp++] = A[sl++]; 24 while (sr <= r) tmpA[tmp++] = A[sr++]; 25 for (int i = 0; i < tmp; i++) A[i + l] = tmpA[i]; 26 } 27 28 int main() { 29 scanf("%d", &n); 30 for (int i = 1; i <= n; i++) scanf("
%lld", &a[i]); 31 32 merge_sort(1, n, a); 33 printf("%lld\n", cnt); 34 35 return 0; 36 }