题目:788. 逆序对的数量
思路:用归并排序,然后当a[i[>a[j]时,ct+=mid-i+1即可,注意要用longlong
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
typed![在这里插入图片描述](https://img-blog.csdnimg.cn/f0c8e2c9eed3414eb39d822e812e62ee.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5bKB5b-n,size_20,color_FFFFFF,t_70,g_se,x_16)
ef long long LL;
int n,a[100010];
LL merge(int l,int r){
if(l>=r) return 0;
int mid=l+r>>1;
LL ct=0;
ct+=merge(l,mid);
ct+=merge(mid+1,r);
int t[100010],k=0;
int i=l,j=mid+1;
while(i<=mid&&j<=r){
if(a[i]<=a[j]) t[k++]=a[i++];
else {
ct+=mid-i+1;
t[k++]=a[j++];
}
}
while(i<=mid) t[k++]=a[i++];
while(j<=r) t[k++]=a[j++];
for(int i=0;i<k;i++){
a[i+l]=t[i];
}
return ct;
}
int main(){
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("%lld",merge(0,n-1));
return 0;
}