POJ 2299 归并排序模板

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 49222   Accepted: 18021

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

 
 
 
 
题意:相邻位置的两个数交换,多少次可以把数组变成从小到大的顺序!
归并排序的思想(线代学的逆序数)!
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define N 500010
#define LL long long
using namespace std;
LL a[N], b[N], sum;
void Merge(int left, int mid, int right)
{
    int i = left, j = mid + 1;
    int k = 0;
    while(i <= mid && j <= right)
    {
        if(a[i] <= a[j])
            b[k++] = a[i++];
        else
        {
            b[k++] = a[j++];
            sum += mid - i + 1;
        }
    }
    while(i <= mid)
        b[k++] = a[i++];
    while(j <= right)
        b[k++] = a[j++];
    for(i = 0; i < k; i++)
        a[left + i] = b[i];
}
void Mysort(int left, int right)
{
    if(left < right)
    {
        int mid = (right + left) / 2;
        Mysort(left, mid);
        Mysort(mid + 1, right);
        Merge(left, mid, right);
    }
}
int main()
{
    int n, i;
    while(scanf("%d", &n), n)
    {
        sum = 0;
        memset(a, 0, sizeof(a));
        for(i = 0; i < n; i++)
            scanf("%lld", &a[i]);
        Mysort(0, n - 1);
        printf("%lld\n", sum);
    }
    return 0;
}

 

posted @ 2015-09-08 15:56  byonlym  阅读(220)  评论(0编辑  收藏  举报