POJ 2299-Ultra-QuickSort(归并排序求相邻元素的交换次数)

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 43816   Accepted: 15979

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

题意:给出一个数列,每次交换相邻数字,求排成递增序的最少交换次数。

思路:本应该是冒泡排序求,但是数值为50w,所以铁定会超时。归并排序可以求序列的逆序数,序列的逆序数=在只允许相邻两个元素交换的条件下,得到有序序列的交换次数

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int input[500010];
int tmp[500010];
long long sum;
void merge(int l,int mid,int r)
{
    int i=l;
    int j=mid+1;
    int k=1;
    while(i<=mid&&j<=r){//这时候i 和 j 指向的部分都排序完毕了 现在合并 
        if(input[i]>input[j]){
            tmp[k++]=input[j++];
            sum+=mid-i+1;////第i个比j大 由于i已经从小到大排过序了 那么i+1到mid的也会比j大
        }
        else
            tmp[k++]=input[i++];
    }
    while(i<=mid)
        tmp[k++]=input[i++];
    while(j<=r)
        tmp[k++]=input[j++];
    for(i=l,k=1;i<=r;i++,k++){
        input[i]=tmp[k];
    }
}
void merge_sort(int l,int r)
{
    if(l<r){//长度大于1  这是个判断不是循环 
        int mid=(l+r)/2;
        merge_sort(l,mid);
        merge_sort(mid+1,r);
        merge(l,mid,r);
    }
}
int main()
{
    int n,i;
    while(~scanf("%d",&n)){
            if(n==0)
            break;
        for(i=0;i<n;i++){
            scanf("%d",&input[i]);
        }
        sum=0;
        merge_sort(0,n-1);
        printf("%lld\n",sum);
    }
    return 0;
}









郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。