POJ2299 Ultra-QuickSort 歸併排序求逆序對

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 51777   Accepted: 19009

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

題意:告訴n個數字,問把他們按照從小到大順序排列好後,需要交換幾次。

使用歸併排序,求一下逆序對的個數就是交換次數,複雜度爲O(nlogn)可以滿足時間限制


#include <iostream>
#include <stdio.h>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>

using namespace std;

int n;
int a[555555],b[555555];
__int64 ans;

void cpy(int le,int ri)
{
    for(int i=le;i<=ri;i++)
        a[i]=b[i];
}

void fun(int le,int mid,int ri)
{
    int i=le,j=mid+1,k=le;

    while(i<=mid && j<=ri)
    {
        if(a[i]<a[j])
        {
            b[k++]=a[i];
            i++;
        }
        else
        {
            b[k++]=a[j];
            j++;
            ans+=mid-i+1;
        }
    }

    while(i<=mid)
    {
        b[k++]=a[i];
        i++;
    }
    while(j<=ri)
    {
        b[k++]=a[j];
        j++;
    }

}

void merg(int le,int ri)
{
    int mid=(ri+le)>>1;

    if(le<ri)
    {
        merg(le,mid);
        merg(mid+1,ri);
        fun(le,mid,ri);
        cpy(le,ri);
    }
}

int main()
{
    while(~scanf("%d",&n),n)
    {
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
        }
        ans=0;
        merg(1,n);

        printf("%I64d\n",ans);
    }
    return 0;
}






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