2012-01-12 19:45:39Morris

[UVA] 10327 - Flip Sort

 Flip Sort 

Sorting in computer science is an important part. Almost every problem can be solved effeciently if sorted data are found. There are some excellent sorting algorithm which has already acheived the lower bound nlgn. In this problem we will also discuss about a new sorting approach. In this approach only one operation ( Flip ) is available and that is you can exchange two adjacent terms. If you think a while, you will see that it is always possible to sort a set of numbers in this way.

The Problem

A set of integers will be given. Now using the above approach we want to sort the numbers in ascending order. You have to find out the minimum number of flips required. Such as to sort "1 2 3" we need no flip operation whether to sort "2 3 1" we need at least 2 flip operations.

The Input

The input will start with a positive integer N ( N<=1000 ). In next few lines there will be N integers. Input will be terminated by EOF.

The Output

For each data set print "Minimum exchange operations : M" where M is the minimum flip operations required to perform sorting. Use a seperate line for each case.

Sample Input

3 
1 2 3
3
2 3 1

Sample Output

Minimum exchange operations : 0
Minimum exchange operations : 2



作法 : MergeSort

#include<stdio.h>
int Sum, A[1000], T[1000];
int Merge(int l, int m, int r) {
    int in1 = l, in2 = m+1;
    int i, j, top = 0, tmp = 0;
    while(in1 <= m && in2 <= r) {
        if(A[in1] <= A[in2])
            T[top++] = A[in1++], Sum += tmp;
        else
            T[top++] = A[in2++], tmp++;
    }
    while(in1 <= m)    T[top++] = A[in1++], Sum += tmp;
    while(in2 <= r)    T[top++] = A[in2++];
    for(i = 0, j = l; i < top; i++, j++)
        A[j] = T[i];
}
int MergeSort(int l, int r) {
    if(l < r) {
        int m = (l+r)/2;
        MergeSort(l, m);
        MergeSort(m+1, r);
        Merge(l, m, r);
    }
}
int main() {
    int i, N;
    while(scanf("%d", &N) == 1) {
        for(i = 0; i < N; i++)
            scanf("%d", &A[i]);
        Sum = 0;
        MergeSort(0, N-1);
        printf("Minimum exchange operations : %d\n", Sum);
    }
    return 0;
}