您的位置:首页 > 其它

HDU 1425 sort

2012-04-30 00:04 369 查看
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

简单水题,但是是首次用哈希表的思想,哈希还需要进一步学习学习。
一般解法:
#include <iostream>
using namespace std;
#include <algorithm>
#include <cstring>
int a[1000010];
bool cmp(int a,int b)
{
    return a>b;
}
int main()
{
    int n,m,i;

    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(a,0,sizeof(a));
        for(i=0;i<n;i++)
        {
            scanf("%d",a+i);
        }
        sort(a,a+n,cmp);
        int flag=0;
        for(i=0;i<n,m>0;m--,i++)
        {
            if(!flag)
            {
                printf("%d",a[i]);
                flag=1;
            }
            else
                printf(" %d",a[i]);
        }
        printf("\n");
    }
    return 0;
}


哈希思想:
#include <iostream>
#include <cstring>
using namespace std;

int hash[1000010];
int main()
{
    int i,n,m,t;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        memset(hash,0,sizeof(hash));
        for(i=0;i<n;i++)
        {
            scanf("%d",&t);
            hash[t+500000]=1;
        }
        int flag=0;
        for(i=1000010;i>0;i--)
        {
            if(hash[i])  
            {  
                printf("%d",i-500000);  
                m--;  
                if(m)
                    printf(" ");  
            }  
            if(m==0) break;
        }
        printf("\n");
    }
    return 0;
}
继续AC吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: