题目链接:https://www.luogu.com.cn/problem/P1908
模板题,求解逆序对数,用到了归并排序的算法。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 500010;
int n;
int a[N], tmp[N];
ll merge_sort(int l, int r){
if (l >= r) return 0;
int mid = (l + r) >> 1;
ll res = merge_sort(l, mid) + merge_sort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r){
if (a[i] <= a[j]) tmp[k ++ ] = a[i ++ ];
else {
res += mid - i + 1;
tmp[k ++ ] = a[j ++ ];
}
}
while (i <= mid ) tmp[k ++ ] = a[i ++ ];
while (j <= r) tmp[k ++ ] = a[j ++ ];
for (int i = l, j = 0; i <= r; i ++ , j ++ ) a[i] = tmp[j];
return res;
}
int main(){
cin >> n;
for (int i = 0; i < n; i ++ ) scanf ("%d", &a[i]);
cout << merge_sort(0, n - 1) << endl;
return 0;
}