zoukankan      html  css  js  c++  java
  • Hash入门

    HDU1425

    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
     
    一开始看到这题,我就直接用sort排序,然后输出了。
    920MS 3640K  差点超时了。
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int N = 1e6+10;
     4 int a[N], n, m;
     5 bool cmp(int x, int y){
     6     return x>y;
     7 }
     8 int main()
     9 {
    10     while(~scanf("%d %d",&n,&m)){
    11         for(int i = 0; i < n; i ++){
    12             scanf("%d",&a[i]);
    13         }
    14         sort(a,a+n,cmp);
    15         for(int i = 0; i < m-1; i ++){
    16             printf("%d ",a[i]);
    17         }
    18         printf("%d
    ",a[m-1]);
    19     }
    20     return 0;
    21 }

    然后用Hash做了下,发现时间快了许多。

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int N = 5e5;
     4 int a[N*2+10], n, m;
     5 bool cmp(int x, int y){
     6     return x>y;
     7 }
     8 int main()
     9 {
    10     while(~scanf("%d %d",&n,&m)){
    11         int tmp;
    12         for(int i = 0; i < n; i ++){
    13             scanf("%d",&tmp);
    14             a[tmp+N] = 1;
    15         }
    16         int ans = 1;
    17         for(int i = 1000000; i >= 0; i --){
    18             if(a[i]){
    19                 if(ans != m){
    20                     ans++;
    21                     printf("%d ",i-N);
    22                 }else{
    23                     printf("%d
    ",i-N);
    24                     break;
    25                 }
    26             }
    27         }
    28     }
    29     return 0;
    30 }

     常用的Hash函数具体有:SDBMHash,RSHash,JSHash,ELFHash,BKDRHash,DJBHash等等。以后要好好的学了。

  • 相关阅读:
    vim的强大,vim设置和插件的使用,脱离windows才是王道
    [VS2013]如何闪开安装VS2013必须要有安装IE10的限制
    常用客户端实现逻辑
    开源控件ViewPagerIndicator学习
    常用设计模式
    主题演讲:未来新趋势电动车
    你最美好的年华
    一度总结
    android线程池ThreadPoolExecutor的理解
    Touch事件or手机卫士面试题整理回答(二)
  • 原文地址:https://www.cnblogs.com/xingkongyihao/p/6939858.html
Copyright © 2011-2022 走看看