POJ2299 Ultra-QuickSort 归并排序求逆序对

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

Description

POJ2299 Ultra-QuickSort 归并排序求逆序对_第1张图片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;
}






你可能感兴趣的:(POJ2299 Ultra-QuickSort 归并排序求逆序对)