Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2794778
  • 博文数量: 471
  • 博客积分: 7081
  • 博客等级: 少将
  • 技术积分: 5369
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-04 21:55
文章分类

全部博文(471)

文章存档

2014年(90)

2013年(69)

2012年(312)

分类: C/C++

2012-04-19 21:35:06

Problem Description
给你n个整数,请按从大到小的顺序输出其中前m大的数。
 
Input
每组测试数据有两行,第一行有两个数n,m(0各不相同,且都处于区间[-500000,500000]的整数。
 
Output
对每组测试数据按从大到小的顺序输出前m大的数。
 
Sample Input
5 3 3 -35 92 213 -644
Sample Output
213 92 3
链接:
 
最简单的哈希,空间换时间!!! 156MS
直接定址法
具体思路:数据量大,数据在一定范围;
hash表(将数据直接映射到地址,这里给了范围[-500000,500000]可以直接定址)

点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<string.h>
  3. #define Max 1000000+10
  4. int hash[Max];

  5. int main()
  6. {
  7.     int n,m;
  8.     while(scanf("%d%d",&n,&m)!=EOF)
  9.     {
  10.         memset(hash,0,sizeof(hash));
  11.         int temp;
  12.         for(int i=0;i<n;i++)
  13.         {
  14.             scanf("%d",&temp);
  15.             hash[500000+temp]=1;//直接定址法ax+b,a b是常数
  16.         }
  17.         int count=0;
  18.         for(int j=Max;j>=0;j--)//从大到小
  19.         {
  20.             if(hash[j]==1)
  21.             {
  22.                 count++;
  23.             
  24.                 if(count<m)
  25.                     printf("%d ",j-500000);    
  26.                 else if(count==m)
  27.                     printf("%d\n",j-500000);    
  28.                 else
  29.                     break;
  30.             }
  31.         }
  32.     }
  33.     return 0;
  34. }

 
阅读(1093) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~