归并排序求逆序数

demo:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<cmath>
#define maxn 500002
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
ll tmp[maxn],a[maxn],n;
ll cnt=0;

void merge(int l,int m,int r){
    int i=l,j=m+1,k=0;
    while(i<=m&&j<=r){
        if(a[i]<=a[j]) tmp[k++]=a[i++];
        else tmp[k++]=a[j++],cnt+=m-i+1; 
    }
    while(i<=m) tmp[k++]=a[i++];
    while(j<=r) tmp[k++]=a[j++];
    for(int i=l;i<=r;i++) a[i]=tmp[i-l];
}

void mergesort(int l,int r){
    if(l<r){
        int mid=(l+r)>>1;
        mergesort(l,mid);
        mergesort(mid+1,r);
        merge(l,mid,r);
    }
}
int main(){
    while(cin>>n&&n){
        cnt=0;
        for(int i=0;i<n;i++) cin>>a[i];
        mergesort(0,n-1);
        printf("%lld\n",cnt);
    }

}

 

posted @ 2018-09-03 00:04  Elpsywk  阅读(144)  评论(0编辑  收藏  举报