POJ 2299 UltraQuickSort

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 32539   Accepted: 11599

Description

In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence 
9 1 0 5 4 ,

Ultra-QuickSort produces the output 
0 1 4 5 9 .

Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.

Input

The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 ≤ a[i] ≤ 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.

Output

For every input sequence, your program prints a single line containing an integer number op, the minimum number of swap operations necessary to sort the given input sequence.

Sample Input

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0
提示:运用归并排序
#include <stdio.h>

int temp[500005];
int a[500005];
long long ans = 0;

void Merge(int arr[], int low, int mid, int high)
{
    int index1 = low;
    int index2 = mid + 1;
    int index3 = 0;
    while(index1 <= mid && index2 <= high)
    {
        if (arr[index1] <= arr[index2])
        {
            temp[index3++] = arr[index1++];
        }
        else
        {
            temp[index3++] = arr[index2++];
            ans += mid + 1 - index1;
        }
    }
    while(index1 <= mid)
    {
        temp[index3++] = arr[index1++];
    }
    while(index2 <= high)
    {
        temp[index3++] = arr[index2++];
    }
     int j;
    for (int i = 0,j = low; j <= high; i++, j++)
    {
        arr[j] = temp[i];
    }
}

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



int main()
{
    int n;
    while(1)
    {
        scanf("%d", &n);
        if (n == 0)
        {
            break;
        }
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        ans = 0;
        MergeSort(a, 0, n - 1);
        printf("%lld\n", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lzmfywz/p/3095125.html