归并排序求逆序数

上机题目问的是冒泡排序的交换次数,实际上就是该数列的逆序数。(原因还没想明白)
#include 
#include 
#define N 500005

int a[N], b[N];
long long ans;
void Merge(int low, int mid, int high)
{
    int i = low, j = mid + 1, k = 0;
    while(i <= mid && j <= high)
    {
        if(a[i] <= a[j])
            b[k++] = a[i++];
        else
        {
            ans += mid - i + 1;//关键点
            b[k++] = a[j++];
        }
    }
    while(i <= mid)
        b[k++] = a[i++];
    while(j <= high)
        b[k++] = a[j++];
    for(k = 0, i = low; i <= high; i++, k++)
        a[i] = b[k];
}

void MergeSort(int low, int high)
{
    int mid;
    if(low < high)
    {
        mid = (low + high) / 2;
        MergeSort(low, mid);
        MergeSort(mid+1, high);
        Merge(low, mid, high);
    }
}

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

你可能感兴趣的:(上机题目整理)