POJ 2229 Ultra-QuickSort 归并排序求逆序数

来源:互联网 发布:js中的换行是什么 编辑:程序博客网 时间:2024/06/05 14:39

题目描述:

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:

59105431230

Sample Output:

60

题目分析:

这道题乍一看是一个求冒泡排序的交换次数,其实看到数据大小很明显是不能用冒泡排序来做的。这道题其实要求我们掌握归并排序以及其运用归并排序来求逆序数的方法。
其中归并排序的具体思想可以看一个大牛的博客:
http://blog.csdn.net/morewindows/article/details/6678165/

代码如下:

#include <iostream>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <algorithm>const int MAXN=500005;const int INF = 0x3f3f3f3f;using namespace std;long long ans;int leftdata[MAXN/2+1], rightdata[MAXN/2+1];void merge(int *a,int start,int mid,int end){    int n1=mid-start+1;    int n2=end-mid;    int c1=0,c2=0;    for(int i=0; i<n1; i++) leftdata[i]=a[start+i];    for(int i=0; i<n2; i++) rightdata[i]=a[mid+1+i];    leftdata[n1]=rightdata[n2]=INF;    for(int t=start; t<=end; t++)    {        if (leftdata[c1]<=rightdata[c2])        {            a[t]=leftdata[c1];            c1++;        }        else        {            a[t]=rightdata[c2];            c2++;            ans+=n1-c1;        }    }    return;}void mergesort(int *a,int start,int end){    int mid;    if (start<end)    {        mid=(start+end)/2;        mergesort(a,start,mid);        mergesort(a,mid+1,end);        merge(a,start,mid,end);    }    return;}int main(){    int a[MAXN];    int n;    while(~scanf("%d",&n) && n)    {        ans=0;        for(int i=0; i<n; i++)        {            scanf("%d",&a[i]);        }        mergesort(a,0,n-1);        printf("%lld\n",ans);    }    return 0;}
0 0
原创粉丝点击