Loading

788. 逆序对的数量(归并排序的应用)

题目链接:

https://www.acwing.com/problem/content/790/

 

题解:

左边部分的下标必定小于右边部分的下标,且左右两边都排好序了,计算即可。

 

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;

typedef long long LL;

const int N = 1e5+5;
int a[N],tmp[N];
int n;

LL merge_sort(int a[],int l,int r){
    if(l >= r) return 0;
    
    int mid = l + r >> 1;
    
    LL res = merge_sort(a,l,mid) + merge_sort(a,mid+1,r);
    
    int k = 0,s1 = l,s2 = mid + 1;
    
    while(s1 <= mid && s2 <= r){
        if(a[s1] <= a[s2]) tmp[k++] = a[s1++];
        else{
            res += mid - s1 + 1;
            tmp[k++] = a[s2++];
        }
    }
    
    while(s1 <= mid) tmp[k++] = a[s1++];
    while(s2 <= r) tmp[k++] = a[s2++];
    
    for(int i=l,j=0;i <= r;i++,j++) a[i] = tmp[j];
    
    return res;
}


int main(){
    scanf("%d",&n);
    
    for(int i=0;i<n;i++) scanf("%d",&a[i]);
    
    LL res = merge_sort(a,0,n-1);
    
    printf("%lld",res);
    
    return 0;
}

 

posted @ 2020-02-14 14:27  Doubest  阅读(140)  评论(0编辑  收藏  举报