逆序对的数量【归并排序】
利用归并排序可以记录逆序数:
#include "bits/stdc++.h"
using namespace std;
#define int long long
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int n,ans;
int x[100005],xx[100005]; //原数组和辅助数组
void merge_sort(int l,int r){
if(l >= r)
return;
int mid = (l + r) >> 1,i = l,j = mid + 1,k = 0;
merge_sort(l,mid),merge_sort(j,r);
while(i <= mid && j <= r)
if(x[i] <= x[j])
xx[k++] = x[i++];
else
xx[k++] = x[j++],ans += (mid - l + 1);
//ans记录逆序数
while(i <= mid)
xx[k++] = x[i++];
while(j <= r)
xx[k++] = x[j++];
for(i = l,j = 0;i <= r;++i,++j)
x[i] = xx[j];
}
signed main(){
IOS
cin>>n;
for(int i = 1;i <= n;++i)
cin>>x[i];
merge_sort(1,n);
cout<<ans;
return 0;
}