归并排序逆序对
作者:
zplzh
,
2024-03-20 10:32:30
,
所有人可见
,
阅读 2
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1E5+9;
int a[N],temp[N];
ll ans;
ll meger(int q[],int l,int r){
if(l>=r) return 0;
int mid = (l+r)>>1,k=0;
int i = l,j = mid+1;
ans = meger(q,l,mid)+meger(q,mid+1,r);
while(i<=mid&&j<=r){
if(q[i]<=q[j]) temp[k++] = q[i++];
else {
ans += mid -i+1;
temp[k++] = q[j++];
}
}
while(i<=mid) temp[k++] = q[i++];
while(j<=r) temp[k++] = q[j++];
for(int i = l,j=0;i<=r;j++,i++) q[i] = temp[j];
return ans;
}
int main(){
int n;
cin>>n;
for(int i = 0;i<n;i++) cin>>a[i];
cout<<meger(a,0,n-1)<<endl;
return 0;
}