poj 2299

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 48121   Accepted: 17553

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

5
9
1
0
5
4
3
1
2
3
0

Sample Output

6
0

Source

題意:
給出n個數,要求求出按照冒泡排序法需要多少次才能把這n個數按從小到大的順序排列。
思路:
需要多少次才能按從小到大的順序排列,可以轉化成求其逆序數(這個線代學過),但是n<=500000,逆序數可能會超過int ,所以結果要用long long ,否則wrong answer.求其逆序數可以用歸併排序,按照分治三步:
1.劃分問題:吧序列分成元素個數儘量相等的兩半。
2.遞歸求解:把元素分別排列。
3.把兩個有序表合併成一個。
中間過程需要引入一個輔助空間T[n].
每一次累加cnt+=m-p;即是答案。
代碼:
#include<cstdio>
#include<cstring>
#include<algorithm>
int  A[500004],T[500004];
long long  cnt;
using namespace std;
void init(int n)
{
    for(int i=0;i<n;i++)
        scanf("%d",&A[i]);

}
void merge_sort(int *A,int x,int y,int *T)
{
    if(y-x>1)
    {
        int m=x+(y-x)/2;
        int p=x,q=m,i=x;
        merge_sort(A,x,m,T);
        merge_sort(A,m,y,T);
        while(p<m||q<y)
        {
            if(q>=y||(p<m&&A[p]<=A[q]))    T[i++]=A[p++];
            else
            {
                T[i++]=A[q++];
                cnt+=m-p;

            }

    }            for(i=x;i<y;i++)
                A[i]=T[i];
}
}
int main()
{
    int n;
    while(scanf("%d",&n)&&n)
    {
       init(n);
       cnt=0;
     memset(T,0,sizeof(T));
     merge_sort(A,0,n,T);//不能把n寫成n-1,否則會答案錯誤
   printf("%I64d\n",cnt);
    }

    return 0;
}


發佈了76 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章