POJ2299 Ultra-QuickSort(归并排序,求逆序数)

来源:互联网 发布:linuxshell编程实例 编辑:程序博客网 时间:2024/05/16 14:32

题目:

Ultra-QuickSort
Time Limit: 7000MS Memory Limit: 65536KTotal Submissions: 59652 Accepted: 22106

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

59105431230

Sample Output

60

Source

Waterloo local 2005.02.05

[Submit]   [Go Back]   [Status]   [Discuss]

思路:

和nyoj归并排序一模一样,还归并排序的时候记录一下距离

代码:

#include <stdio.h>#include <string.h>#include <string>#include <iostream>#include <stack>#include <cmath>#include <queue>#include <vector>#include <algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define N 500000+20#define M 1000000+10#define LL long longusing namespace std;LL sum;LL a[N],b[N];void mix(LL start,LL mid,LL end){    LL i=start,j=mid+1,k=0;    while(i<=mid&&j<=end)    {        if(a[i]<=a[j])        {            b[k++]=a[i++];        }        else        {            sum+=mid+1-i;            b[k++]=a[j++];        }    }    while(i!=mid+1)        b[k++]=a[i++];    while(j!=end+1)        b[k++]=a[j++];    for(LL i=0; i<k; i++)        a[start++]=b[i];}void mergesort(LL start,LL end){    LL mid=(start+end)/2;    if(start<end)    {        mergesort(start,mid);        mergesort(mid+1,end);        mix(start,mid,end);    }}int main(){    LL n;    while(~scanf("%lld",&n)&&n)    {        sum=0;        for(LL i=0; i<n; i++)            scanf("%lld",&a[i]);        mergesort(0,n-1);        printf("%lld\n",sum);    }    return 0;}


0 0
原创粉丝点击