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

题目描述:

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

题目分析:

这道题乍一看是一个求冒泡排序的交换次数,其实看到数据大小很明显是不能用冒泡排序来做的。这道题其实要求我们掌握归并排序以及其运用归并排序来求逆序数的方法。
其中归并排序的具体思想可以看一个大牛的博客:
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值