poj 1804 Brainman

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;
typedef long long LL;
const int MAXN = 1010;

int a[MAXN], b[MAXN];
LL sum;

void Merge(int low, int mid, int high)
{
    int i = low, j = mid+1, k = low;

    while(i <= mid && j <= high)
    {
        if(a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++], sum += (mid - i + 1);
    }

    while(i <= mid)
        b[k++] = a[i++];
    while(j <= high)
        b[k++] = a[j++];
    for(int i = low; i <= high; ++i)
        a[i] = b[i];
    return ;
}

void Merge_Sort(int low, int high)
{
    if(low == high)
        return ;
    if(low < high)
    {
        int mid = (low + high) >> 1;
        Merge_Sort(low, mid);
        Merge_Sort(mid+1, high);
        Merge(low, mid, high);
    }
    return ;
}

int main()
{
    int T, kcase = 1;
    int n;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        for(int i = 0; i < n; ++i)
            scanf("%d", &a[i]);
        sum = 0;
        Merge_Sort(0, n-1);
        printf("Scenario #%d:\n%I64d\n\n", kcase++,sum);
    }
    return 0;
}

你可能感兴趣的:(归并排序,逆序数)