逆序對的數量(歸併排序模板)

Biang-Biang發表於2020-10-25

題目連結:https://www.acwing.com/problem/content/790/
歸併排序詳解:https://blog.csdn.net/weixin_45758110/article/details/109252365

思路:在二路歸併的過程中,如果出現a[i]>a[j],則sum+=mid-i+1(加上左邊區間大於a[j]的個數)

#include<cstdio>
#include<iostream>
using namespace std;
const int maxn=1e5+5;
int a[maxn],tmp[maxn];
long long t=0;
void merge_sort(int a[], int l ,int r){
    if(l>=r)return ;
    int mid=l+r>>1;
    int k=0,i=l, j=mid+1;
    merge_sort(a,i,mid); merge_sort(a,mid+1,r);
    while(i<=mid&&j<=r){
        if(a[i]<=a[j])tmp[k++]=a[i++];
        else{
            tmp[k++]=a[j++];
            t+=mid-i+1;
        }
    }
    while(i<=mid)tmp[k++]=a[i++];
    while(j<=r) tmp[k++]=a[j++];
    for(i=l,j=0;i<=r;i++,j++)a[i]=tmp[j];
}
int main(){
    int n; scanf("%d",&n);
    for(int i=0;i<n;i++)scanf("%d",&a[i]);
    merge_sort(a,0,n-1);
    printf("%lld",t);
    return 0;
}

相關文章