• hdu acm 1425 sort(哈希表思想)


    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
    Hint
    Hint
    请用VC/VC++提交
     
    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("
    ");
    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("
    ");
    31     }
    32     return 0;
    33 }


    对比:


    上为哈希表,下为普通做法。可看出差别很大

  • 相关阅读:
    北风设计模式课程---行为型模式总结
    北风设计模式课程---21、中介者模式
    kindeditor-网页文字编辑
    CSDN挑战编程——《金色十月线上编程比赛第二题:解密》
    Unreal Engine 4 创建Destructible Mesh(可破坏网格)
    android弹出时间选择框
    mac_Mac环境下怎样编写HTML代码?
    PL/SQL 游标的使用
    [cocos2dx笔记008]cocos2d 用luabridge手动绑定类
    Codeforces Round #274 (Div. 2)
  • 原文地址:https://www.cnblogs.com/vivider/p/3702674.html
Copyright © 2020-2023  润新知