AcWing 788. 逆序对的数量
原题链接
简单
作者:
Sky_
,
2020-10-22 14:54:41
,
所有人可见
,
阅读 329
#include <iostream>
#include <cstdio>
using namespace std;
const int maxlen = 100010;
long long res = 0;
int merge_sort(int *nums, int l, int r)
{
if(l>=r) return 0;
int mid = l+r>>1;
merge_sort(nums, l, mid); merge_sort(nums, mid+1, r);
int k = 0, i=l, j=mid+1;
int tmp[maxlen];
while(i<=mid && j<=r)
{
if(nums[i]<=nums[j]) tmp[k++] = nums[i++];
else
{
res += mid-i+1;
tmp[k++] = nums[j++];
}
}
while(i<=mid) tmp[k++] = nums[i++];
while(j<=r) tmp[k++] = nums[j++];
for(i=l,j=0; i<=r; i++, j++) nums[i] = tmp[j];
}
int main()
{
int arr[maxlen];
int len;
cin>>len;
for(int i=0; i<len; i++) cin>>arr[i];
merge_sort(arr, 0, len-1);
//for(int i=0; i<len; i++) cout<<arr[i]<<" ";
cout<<res;
return 0;
}