poj2299 Ultra-QuickSort

来源:互联网 发布:mac怎么创建html文件 编辑:程序博客网 时间:2024/05/23 02:00

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.

可以转化成经典的归并排序求逆序对个数。
结果是long long。

#include<cstdio>#include<cstring>#define M(a) memset(a,0,sizeof(a))long long a[500010],tem[500010],ans;int n;void mg(int l,int r){    if (l==r) return;    int mid=(l+r)/2;    mg(l,mid);    mg(mid+1,r);    int i=l,j=mid+1,p=l;    while (i<=mid||j<=r)    {        if (i>mid)        {            tem[p++]=a[j++];            continue;        }        if (j>r)        {            tem[p++]=a[i++];            continue;        }        if (a[i]<=a[j])          tem[p++]=a[i++];        else        {            tem[p++]=a[j++];            ans+=mid-i+1;        }    }    for (i=l;i<=r;i++)      a[i]=tem[i];}int main(){    int i,j,k;    while (scanf("%d",&n)&&n)    {        M(a);        ans=0;        for (i=1;i<=n;i++)          scanf("%lld",&a[i]);        mg(1,n);        printf("%lld\n",ans);    }}
0 0
原创粉丝点击