[51nod] 1019 逆序数

要点:左右分治

注解:使用了归并排序

空间复杂度:NlogN

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

int val[1000000] = {0};
int tmp[1000000] = {0};
int ans = 0;

void mergesort(int L,int R){
    if(L == R) return;
    mergesort(L,(L+R)/2);
    mergesort((L+R)/2+1,R);
    
    int p = L,lp = L,rp = (L+R)/2+1;
    while(p <= R){
        if(lp > (L+R)/2) tmp[p++] = val[rp++];
        else if(rp > R) tmp[p++] = val[lp++];
        else if(val[lp] <= val[rp]) tmp[p++] = val[lp++];
        else if(val[lp] > val[rp]) tmp[p++] = val[rp++],ans+=(L+R)/2-lp+1;
    }

    for(int i = L;i <= R;i++) val[i] = tmp[i];
}

int main(){
    int n;
    scanf("%d",&n);
    for(int i = 1;i <= n;i++) scanf("%d",&val[i]);
    if(n == 1) ans = 1;
    mergesort(1,n);
    printf("%d\n",ans);
//    for(int i = 1;i <= n;i++) printf("%d ",val[i]);
    return 0;
}
View Code

 

posted @ 2019-12-06 19:51  μSsia  阅读(140)  评论(0编辑  收藏  举报