hdu acm 1425 sort(哈希表思想)
时间:2014-05-01 20:50:16
收藏:0
阅读:583
sort
Time
Limit: 6000/1000 MS (Java/Others) Memory Limit:
65536/32768 K (Java/Others)
Total Submission(s):
25803 Accepted Submission(s):
7764
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
请用VC/VC++提交
Hint
Hint
Author
LL
最简单的运用了哈希表的思想的题,开始看了好多关于散列的理论资料,太深奥反而抓不住基本思想。
基本做法
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 bool cmp(int x,int y) 7 { 8 return x>y; 9 } 10 11 int a[1000000]; 12 13 int main() 14 { 15 int n,k; 16 while(~scanf("%d%d",&n,&k)) 17 { 18 for(int i = 0;i<n;i++) 19 scanf("%d",&a[i]); 20 sort(a,a+n,cmp); 21 printf("%d",a[0]); 22 for(int i = 1;i<k;i++) 23 printf(" %d",a[i]); 24 printf("\n"); 25 } 26 27 return 0; 28 }
哈希表思想(空间换时间)
1 #include <iostream> 2 #include <cstring> 3 #include <stdio.h> 4 using namespace std; 5 6 int hash[1000010]; 7 int main() 8 { 9 int i,n,m,t; 10 while(scanf("%d%d",&n,&m)!=EOF) 11 { 12 memset(hash,0,sizeof(hash)); 13 for(i=0;i<n;i++) 14 { 15 scanf("%d",&t); 16 hash[t+500000]=1; 17 } 18 int flag=0; 19 for(i=1000010;i>0;i--) 20 { 21 if(hash[i]) 22 { 23 printf("%d",i-500000); 24 m--; 25 if(m) 26 printf(" "); 27 } 28 if(m==0) break; 29 } 30 printf("\n"); 31 } 32 return 0; 33 }
对比:
上为哈希表,下为普通做法。可看出差别很大
评论(0)