POJ 2299 Ultra-QuickSort

求快排的交换次数,也就是逆序数

写个归并排序来算就ok了,注意逆序数会超int

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
long long a[500100],b[500100];
long long MergeSort(long long s,long long e)
{
    long long mid,cnt,t1,t2,i;
    if (s >= e-1)
        return 0;
    mid=(s+e)>>1;
    cnt=MergeSort(s,mid)+MergeSort(mid,e);
    t1=s;
    t2=mid;
    i=s;
    while (t1 < mid && t2 < e)
    {
        if (a[t1] < a[t2])
        {
            b[i]=a[t1];
            t1++;
            i++;
            cnt+=t2-mid;
        }
        else
        {
            b[i]=a[t2];
            t2++;
            i++;
        }
    }
    while (t1 < mid)
    {
        b[i]=a[t1];
        i++;
        t1++;
        cnt+=t2-mid;
    }
    while (t2 < e)
    {
        b[i]=a[t2];
        i++;
        t2++;
    }
    for (i=s; i<e; i++)
        a[i]=b[i];
    return cnt;
}
int main()
{
    long long n,i,j;
    while (1)
    {
        scanf("%lld",&n);
        if (n == 0)
            break;
        for (i=0; i<n; i++)
            scanf("%lld",a+i);
        printf("%lld\n",MergeSort(0,n));
    }
}

你可能感兴趣的:(POJ 2299 Ultra-QuickSort)