poj-2299

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 80412   Accepted: 30110

Description

poj-2299_第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

Source

Waterloo local 2005.02.05

OJ-ID: poj-2299
author:Caution_X
date of submission:20191121
tags:merge_sort
description modelling:
计算将一个数列变成正序数列至少需要几次操作。
操作:交换相邻两个数的位置
major steps to solve it:
(1)归排
(2)在归排的子过程中若出现ia[j],ans+=(j-j即将变换到的位置)。
warnings:
AC code:
#include
#include
using namespace std;
int a[500005];
int tmp[500005];
long long int num = 0;
void merge(int left, int mid, int right)
{
    int i = left, j = mid + 1, n = left;
    while (i <= mid && j <= right)
    {
        if (a[i] > a[j])
        {
            tmp[n++] = a[j++];
            num += (j - n);
        }
        else
        {
            tmp[n++] = a[i++];
        }
    }
    if (i > mid)
    {
        while (j <= right)
            tmp[n++] = a[j++];
    }
    else
    {
        while (i <= mid)
            tmp[n++] = a[i++];
    }
    for (int k = left; k <= right; k++)
    {
        a[k] = tmp[k];
    }
}
void mergesort(int left, int right)
{
    if (left < right)
    {
        int mid = (left + right) / 2;
        mergesort(left, mid);
        mergesort(mid + 1, right);
        merge(left, mid, right);
    }
}
int main()
{
    int n;
    //freopen("input.txt", "r", stdin);
    while (~scanf("%d", &n) && n)
    {
        num = 0;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
        }
        mergesort(0, n - 1);
        printf("%lld\n", num);
    }
    return 0;
}

你可能感兴趣的:(poj-2299)