24h購物| | PChome| 登入
2012-01-12 19:45:39| 人氣940| 回應0 | 上一篇 | 下一篇

[UVA] 10327 - Flip Sort

推薦 0 收藏 0 轉貼0 訂閱站台

 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;
}

 

台長: Morris
人氣(940) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 11089 - Fi-binary Number
此分類上一篇:[UVA] 11172 - Relational Operator

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文