码迷,mamicode.com
首页 > 其他好文 > 详细

poj 2299

时间:2015-08-03 16:53:35      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

Ultra-QuickSort
Time Limit: 7000MS   Memory Limit: 65536K
Total Submissions: 48121   Accepted: 17553

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

题意:
给出n个数,要求求出按照冒泡排序法需要多少次才能把这n个数按从小到大的顺序排列。
思路:
需要多少次才能按从小到大的顺序排列,可以转化成求其逆序数(这个线代学过),但是n<=500000,逆序数可能会超过int ,所以结果要用long long ,否则wrong answer.求其逆序数可以用归并排序,按照分治三步:
1.划分问题:吧序列分成元素个数尽量相等的两半。
2.递归求解:把元素分别排列。
3.把两个有序表合并成一个。
中间过程需要引入一个辅助空间T[n].
每一次累加cnt+=m-p;即是答案。
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
int  A[500004],T[500004];
long long  cnt;
using namespace std;
void init(int n)
{
    for(int i=0;i<n;i++)
        scanf("%d",&A[i]);

}
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++];
                cnt+=m-p;

            }

    }            for(i=x;i<y;i++)
                A[i]=T[i];
}
}
int main()
{
    int n;
    while(scanf("%d",&n)&&n)
    {
       init(n);
       cnt=0;
     memset(T,0,sizeof(T));
     merge_sort(A,0,n,T);//不能把n写成n-1,否则会答案错误
   printf("%I64d\n",cnt);
    }

    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

poj 2299

标签:

原文地址:http://blog.csdn.net/a1967919189/article/details/47257677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!