POJ 2299

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 24722   Accepted: 8847

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.
罪過,罪過。。。
在網上找的一個歸併排序的模版。。。。。
#include<stdio.h>
#include<string.h>
#include<iostream>

#define maxn 500010
int a[maxn],left[maxn],right[maxn];
long long ans;


void merge(int a[],int p,int q,int r)
{
   int   n1=q-p+1;
   int   n2=r-q;
   int   i,j,k;

    for(i=1;i<=n1;i++)
          left[i]=a[p+i-1];
    for(j=1;j<=n2;j++)
           right[j]=a[q+j];

     left[n1+1]=1e9;    //設置一個哨兵
     right[n2+1]=1e9; //同上
     i=1;
     j=1;
    for(k=p;k<=r;k++)
        if(left[i]<right[j])
                 a[k]=left[i++];
        else
            {
              a[k]=right[j++];
              ans+=n1-i+1;      //計數;
          }
}

void mergesort(int a[],int p,int r)
{
   if(p<r)
   {
       int q=(p+r)/2;
       mergesort(a,p,q);
       mergesort(a,q+1,r);
       merge(a,p,q,r);    //合併步驟 p<=left<=q q<right<=r;
   }
}

int init()
{
    int i,n;
    scanf("%d",&n);
    if (n == 0) return 0;
    memset(a,0,sizeof(a));
    for(i = 1;i <= n;i++) scanf("%d",&a[i]);
    ans = 0;
    mergesort(a,1,n);
    printf("%lld\n",ans);
    return 1;
}

int main()
{
    while (init()) ;
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章