zoukankan      html  css  js  c++  java
  • Ultra-QuickSort

    Ultra-QuickSort

    题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=85904#problem/A

    题目:

         

    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


    题意:
    给出一个序列,求这个序列的逆序对个数。
    方法:
    用归并排序(时间复杂度为O(nlongn))法进行排序,然后在排序过程中计数即可。
    #include<iostream>
    using namespace std;
    const int maxn=500010;
    long long a[maxn],b[maxn],count=0;
    int n;
    void merge(long long*A,int x,int y,long long*T)
    {
        if(y-x>1)
        {
           int m=x+(y-x)/2;
            int p=x,q=m,i=x;
             merge(A,x,m,T);
             merge(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++];
                           count+=m-p;
                       }
                }
                for(int j=x;j<y;j++)
                    A[j]=T[j];
        }
    }
    
    int main()
    {
        while(cin>>n&&n)
        {    
        count=0;
        for(int j=0;j<n;j++)
            cin>>a[j];
       merge(a,0,n,b);
        cout<<count<<endl;
        }
    return 0;
    }



  • 相关阅读:
    Java中字符串中子串的查找共有四种方法(indexof())
    idea常用快捷键
    用hive或mr清洗app数据
    使用kafka作为生产者生产数据到hdfs(单节点)
    使用kafka作为生产者生产数据到hdfs
    c++ map的使用
    c++ set集合的使用
    c++ 木块问题
    c++ 大理石
    c 蛇形数字
  • 原文地址:https://www.cnblogs.com/fenhong/p/4713193.html
Copyright © 2011-2022 走看看