[ACM]Ultra-QuickSort

Time Limit: 7000MS Memory Limit: 65536KB
Total Submissions: 20 Accepted: 7

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

Hint:

Source:

Waterloo local 2005.02.05

 

这题没有什么可说的,直接调用系统的排序函数进行排序就行了,代码如下:

#include <iostream>
#include <algorithm>
using namespace std;

#define MAXN 500001

int a[MAXN],t[MAXN],n;
__int64 ans;

void Merge(int l,int m,int r){
    int i=0,j=l,k=m+1;
    while(j<=m && k<=r){
        if(a[j]>a[k]){
            t[i++]=a[k++];
            ans+=m-j+1;
        }
        else
            t[i++]=a[j++];
    }
    while(j<=m)
        t[i++]=a[j++];
    while(k<=r)
        t[i++]=a[k++];
    for(j=0;j<i;j++){
        a[l+j]=t[j];
    }
}


void 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;
    while(scanf("%d",&n) && n){
        ans=0;
        for(i=0;i<n;i++)
            scanf("%d",a+i);
        Mergesort(0,n-1);
        printf("%I64d
",ans);
    }
    return 0;
}

posted on 2010-03-28 14:57  小橋流水  阅读(180)  评论(0编辑  收藏  举报

导航