POJ 2229 Ultra-QuickSort集計ソート逆シーケンス数を求める


タイトルの説明:
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

テーマ分析:
この問題は一見バブルソートを求める交換回数であるが,実際にはデータサイズがバブルソートではできないことが明らかになった.この問題は実際には,集計ソートとその集計ソートを用いて逆序数を求める方法を把握することを要求している.その中の集計順位の具体的な思想は大牛のブログを見ることができます:http://blog.csdn.net/morewindows/article/details/6678165/
コードは次のとおりです.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
const int MAXN=500005;
const int INF = 0x3f3f3f3f;

using namespace std;
long long ans;
int leftdata[MAXN/2+1], rightdata[MAXN/2+1];
void merge(int *a,int start,int mid,int end)
{
    int n1=mid-start+1;
    int n2=end-mid;
    int c1=0,c2=0;
    for(int i=0; i<n1; i++) leftdata[i]=a[start+i];
    for(int i=0; i<n2; i++) rightdata[i]=a[mid+1+i];
    leftdata[n1]=rightdata[n2]=INF;
    for(int t=start; t<=end; t++)
    {
        if (leftdata[c1]<=rightdata[c2])
        {
            a[t]=leftdata[c1];
            c1++;
        }
        else
        {
            a[t]=rightdata[c2];
            c2++;
            ans+=n1-c1;
        }
    }
    return;
}

void mergesort(int *a,int start,int end)
{
    int mid;
    if (start<end)
    {
        mid=(start+end)/2;
        mergesort(a,start,mid);
        mergesort(a,mid+1,end);
        merge(a,start,mid,end);
    }
    return;
}

int main()
{
    int a[MAXN];
    int n;
    while(~scanf("%d",&n) && n)
    {
        ans=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
        mergesort(a,0,n-1);
        printf("%lld
",ans); } return 0; }