AcWing 788. 逆序对的数量
原题链接
简单
作者:
lngstart
,
2020-02-03 20:34:16
,
所有人可见
,
阅读 675
#include <iostream>
using namespace std;
typedef long long ll;
const int N = 100010;
int n, q[N], temp[N];
ll megerSort(int l, int r) {
if (l >= r) return 0;
int mid = l + r >> 1;
ll ret = megerSort(l, mid) + megerSort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r) {
if (q[i] <= q[j]) temp[k++] = q[i++];
else {
ret += mid - i + 1;
temp[k++] = q[j++];
}
}
while (i <= mid) temp[k++] = q[i++];
while (j <= r) temp[k++] = q[j++];
for (i = l, j = 0; i <= r; ++i, ++j) q[i] = temp[j];
return ret;//不传给上一层的话,就断掉了,所以要return
}
int main() {
cin >> n;
for (int i = 0; i < n; ++i)
cin >> q[i];
cout << megerSort(0, n - 1) << endl;
return 0;
}