您的位置:首页 > 理论基础 > 计算机网络

hdu1425 sort 解题报告

2010-08-19 09:58 85 查看
 Problem Description

给你n个整数,请按从大到小的顺序输出其中前m大的数。

 
 

Input

每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含n个各不相同,且都处于区间[-500000,500000]的整数。

 
 

Output

对每组测试数据按从大到小的顺序输出前m大的数。

 
 

Sample Input

5 3 3 -35 92 213 -644

 
 

Sample Output

213 92 3
解题思路:刚看到这个题,数据那么大,就觉得用排序方法应该是会超时的,所以就选了快速排序试一试的心态,最终是没有达到效果,后来网络里搜一下,知道了另一种对数据的处理方法,直接把数据弄到数组里,就相当于已经排序了,这是一种不普通的解法,还是异于寻常的。速度还是非常的快。我的快速排序的代码如下:Code:#include<iostream>  
using namespace std;  
int a[1000001]={0};  
int n,m;  
  
int Partition(int a[],int low,int high)      //进行一趟的排序  
{  
    int pre=a[low];  
    while(low<high)  
    {  
        while(low<high&&a[high]>=pre)  
            high--;  
        int temp;  
        temp=a[low];  
        a[low]=a[high];  
        a[high]=temp;  
        while(low<high&&a[low]<=pre)  
            low++;  
        temp=a[low];  
        a[low]=a[high];  
        a[high]=temp;  
    }  
    return low;  
}  
  
void QSort(int a[],int low,int high)        //递归  
{  
      
    if(low<high)  
    {  
        int pivotloc=Partition(a,low,high);  
        QSort(a,low,pivotloc-1);  
        QSort(a,pivotloc+1,high);  
    }  
}  
  
void QuickSort(int a[],int j)  
{  
    QSort(a,1,j-1);  
}  
  
int main()  
{  
    int temp;  
      
    while(cin>>n>>m)  
    {  
        int j=1;  
        for(int i=1;i<=n;i++)  
        {  
            cin>>temp;  
            if(temp>=m)  
            {  
                a[j]=temp;  
                j++;  
            }  
        }  
        QuickSort(a,j);  
        for(i=j-1;i>0;i--)  
            cout<<a[i]<<endl;  
    }  
    return 0;  
}  
推荐AC的方法(代码如下):Code:#include <stdio.h>  
int main()  
{  
    unsigned n, m;  
    int x;  
    char a[1000001] = {0};  
    while (scanf("%d%d", &n, &m) != EOF)  
    {  
        while (n--)  
        {  
            scanf("%d", &x);  
            a[500000+x]++;  
        }  
        for (x = 1000000; m; x--)  
        {  
            if (a[x])  
            {  
                printf("%d", x-500000);  
                if (--m)  
                    putchar(32);  
                else  
                    putchar(10);  
                a[x]--;  
            }  
        }  
    }  
    return 0;  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  output input 测试 网络