zoukankan      html  css  js  c++  java
  • ACM归并排序

    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
    解题思路:
    题目大意是输入个数字,将他们按从小到大的顺序排列,问需要经过多少次的交换。这个题目我们要用归并排序的方法解决。
    介绍一下归并排序:1、把序列分成元素个数尽量相等的两半;2、把两半的元素分别排序;3、把两个有序表合并成一个。归并排序的时间复杂度为O(nlogn)
    注意事项:只要有一个序列非空,就要继续合并。
    #include<cstdio>
    #include<cstring>
    #include<iostream>
    #include<algorithm>
    int  A[500004],T[500004];
    long long  s;
    using namespace std;
    void merge_sort(int *A,int x,int y,int *T)
    {
        if(y-x>1)
        {
            int m=x+(y-x)/2;
            int p=x,q=m,i=x;
            merge_sort(A,x,m,T);
            merge_sort(A,m,y,T);
            while(p<m||q<y)
            {
                if(q>=y||(p<m&&A[p]<=A[q]))//只要一个序列为空就要继续合并
                    T[i++]=A[p++];
                else
                {
                    T[i++]=A[q++];
                    s=s+m-p;
    
                }
            }
            for(i=x;i<y;i++)
                A[i]=T[i];
        }
    }
    int main()
    {
        int n;
        while(scanf("%d",&n)&&n)
        {
            for(int i=0;i<n;i++)
                scanf("%d",&A[i]);
            s=0;
            //memset(T,0,sizeof(T));
            merge_sort(A,0,n,T);//不能把n写成n-1,否则会答案错误
            printf("%I64d
    ",s);
        }
    
        return 0;
    }
    
    
    



  • 相关阅读:
    html5学习系列之ef类标签
    html5学习系列之cd标签
    Java学习系列——xml学习基础
    html5学习系列——b标签
    为什么我要使用Linux,使用Linux的十个理由。
    设置Linux系统的空闲等待时间TMOUT的方法和Linux反空闲设置的两种方法
    创建动态MSSQL数据库表的方法
    SQL SERVER 自增列的方法
    XtraBackup构建MySQL主从环境的方法
    如何查看MySQL执行计划呢?
  • 原文地址:https://www.cnblogs.com/xinxiangqing/p/4702405.html
Copyright © 2011-2022 走看看