AcWing 788. 逆序对的数量
原题链接
简单
作者:
__43
,
2020-09-23 12:09:05
,
所有人可见
,
阅读 415
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
typedef long long ll;
int q[N],temp[N];
ll merger_sort(int q[],int l,int r)
{
if (l >= r)
return 0;
int m = l + (r - l) / 2;
ll ans = merger_sort(q,l,m) + merger_sort(q,m + 1,r);
int k = l,i = l,j = m + 1;
while (i <= m && j <= r)
{
if (q[i] <= q[j]) temp[k++] = q[i++];
else ans += (m - i + 1),temp[k++] = q[j++];
}
while (i <= m) temp[k++] = q[i++];
while (j <= r) temp[k++] = q[j++];
for (k = l;k <= r;++k) q[k] = temp[k];
return ans;
}
int main(void)
{
int n;
scanf("%d",&n);
for (int i = 0;i < n;++i)
scanf("%d",&q[i]);
printf("%lld",merger_sort(q,0,n - 1));
return 0;
}