POJ - 2299 Ultra-QuickSort (归并排序)

题意:给你一个序列,让你求出这个序列的逆序数

思路:归并排序的应用,将一个序列分成左右两个部分,当右边退出的话,那么此时左边还有几个,就代表这个数有几个逆序数

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int MAXN = 1000010;

int a[MAXN],t[MAXN],n;
long long sum;

void merge(int low,int mid,int high){
    int k,begin1,begin2,end1,end2;
    begin1 = low;
    end1 = mid;
    begin2 = mid + 1;
    end2 = high;
    for (k = 0; begin1 <= end1 && begin2 <= end2; k++){
        if (a[begin1] <= a[begin2])
            t[k] = a[begin1++];
        else {
            t[k] = a[begin2++];
            sum += mid - begin1 + 1;
        }
    }
    if (begin1 <= end1)
        memcpy(t+k,a+begin1,(end1-begin1+1)*sizeof(int));
    else memcpy(t+k,a+begin2,(end2-begin2+1)*sizeof(int));
    memcpy(a+low,t,(high-low+1)*sizeof(int));
}

void merge_sort(int begin,int end){
    int mid;
    if (begin < end){
        mid = (begin+end) >> 1;
        merge_sort(begin,mid);
        merge_sort(mid+1,end);
        merge(begin,mid,end);
    }
}

int main(){
    int t;
    while (scanf("%d",&n) != EOF && n){
        sum = 0;
        for (int i = 0; i < n; i++)
            scanf("%d",&a[i]);
        merge_sort(0,n-1);
        printf("%lld\n",sum);
    }
    return 0;
}




你可能感兴趣的:(POJ - 2299 Ultra-QuickSort (归并排序))