zoukankan      html  css  js  c++  java
  • Ultra-QuickSort(归并排序)

    Ultra-QuickSort
    Time Limit: 7000MS   Memory Limit: 65536K
    Total Submissions: 49267   Accepted: 18035

    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
    题解,错了半天,while出错,改成for循环就对了,至今不知道为啥。。。
    代码:
     1 #include<stdio.h>
     2 const int MAXN=500010;
     3 int a[MAXN],b[MAXN];
     4 long long ans;
     5 void mergesort(int start,int mid,int end){
     6     int i=start,k=start,j=mid+1;
     7     while(i<=mid&&j<=end){
     8         if(a[i]<=a[j])b[k++]=a[i++];
     9         else{
    10             ans+=j-k;
    11             b[k++]=a[j++];
    12         }
    13     }
    14         while(i<=mid)b[k++]=a[i++];
    15         while(j<=end)b[k++]=a[j++];
    16         //while(start<=end)a[start++]=b[start];    
    17         for(int i=start;i<=end;i++)a[i]=b[i];
    18 } 
    19 void ms(int l,int r){
    20     if(l<r){
    21         int mid=(l+r)/2;
    22         ms(l,mid);
    23         ms(mid+1,r);
    24         mergesort(l,mid,r);
    25     }
    26 }
    27 int main(){
    28     int n;
    29     while(scanf("%d",&n),n){
    30         ans=0;
    31         for(int i=1;i<=n;i++)scanf("%d",a+i);
    32         ms(1,n);
    33         printf("%lld
    ",ans);
    34     }
    35     return 0;
    36 }

  • 相关阅读:
    JAVA课程设计+五子棋游戏
    201521123059 《Java程序设计》第十四周学习总结
    201521123059 《Java程序设计》第十三周学习总结
    软工个人总结
    alpha阶段个人总结
    centos 下构建lamp环境
    软工15作业3——案例分析
    结对编程
    201521123058 软工阅读第二次作业
    软工阅读作业1(201521123058 李绍乐)
  • 原文地址:https://www.cnblogs.com/handsomecui/p/4804070.html
Copyright © 2011-2022 走看看