【归并排序】AcWing 788. 逆序对的数量

788. 逆序对的数量 - AcWing题库

 

#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
typedef long long ll;
const int N=1e5+10;
int q[N],tmp[N],n;
ll mergeSort(int l,int r){
    if(l>=r) return 0;
    int  mid=l+r>>1;
    ll ans=mergeSort(l,mid)+mergeSort(mid+1,r);
    int k=0,i=l,j=mid+1;
    while(i<=mid&&j<=r){
        if(q[i]<=q[j]) tmp[k++]=q[i++];
        else{
            tmp[k++]=q[j++];
            ans+=mid-i+1;
        }
    }
    while(i<=mid) tmp[k++]=q[i++];
    while(j<=r) tmp[k++]=q[j++];
    for(int i=l,j=0;i<=r;i++,j++) q[i]=tmp[j];
    return ans;
}
int  main(){
    cin>>n;
    rep(i,0,n-1) cin>>q[i];
    cout<<mergeSort(0,n-1);
}

 

上一篇:cf1530-CodeforcesRound733(div1+div2)


下一篇:【UOJ649】游泳