AcWing 788. 逆序对的数量
原题链接
简单
作者:
KaiWings-X
,
2024-07-26 18:34:35
,
所有人可见
,
阅读 2
#include<iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
int q[N], tmp[N];
int n;
LL res = 0;
LL merge_sort(int q[], int l, int r)
{
if(l == r) return 0;
else
{
int mid = l + r >> 1;
res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r);
int k = l, i = l, j = mid + 1;
while(i <= mid && j <= r)
{
if(q[i] <= q[j]) tmp[k++] = q[i++];
else
{
tmp[k++] = q[j++];
res += mid - i + 1;
}
}
while(i <= mid) tmp[k++] = q[i++];
while(j <= r) tmp[k++] = q[j++];
for(int i = l; i <= r; i++) q[i] = tmp[i];
return res;
}
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &q[i]);
// merge_sort(q, 0, n - 1);
// cout << res <<endl;
cout<<merge_sort(q, 0, n - 1) << endl;
return 0;
}