Inverse Pair_算法

#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,m;
int x[200005];
int t[400005];
set<int> s;
//归并排序求逆序数
void merge_sort_inversion(int *A,int l,int r,int *T,int *cnt){
if (r-l>1) {
int m=l+(r-l)/2; //划分
int p=l,q=m,i=l;
merge_sort_inversion(A, l, m, T,cnt); //递归求解
merge_sort_inversion(A, m, r, T,cnt); //递归求解
while (p<m||q<r)
if (q>=r||(p<m&&A[p]<=A[q]))
T[i++]=A[p++]; //从左半数组复制到临时空间
else{
T[i++]=A[q++]; //从右半数组复制到临时空间
*cnt += m-p;
}
for (i=l; i<r; i++)
A[i]=T[i]; //从辅助空间复制回A数组
}
}

void solve(){
cin>>n;
for(int i = 1;i <= n;++i)
cin>>x[i];
for(int i = 1;i <= n;++i){
if(s.count(x[i] + 1) != 0)
++x[i];
s.insert(x[i]);
}
int ans = 0;
merge_sort_inversion(x,1,n + 1,t,&ans);
cout<<ans;
}
signed main(){
IOS;
int tt = 1;
//cin>>tt;
while(tt--)
solve();
return 0;
}