hdu1280(比m大的数)---哈希表

来源:互联网 发布:无主之地淘宝 编辑:程序博客网 时间:2024/05/01 03:19

前m大的数

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 11163    Accepted Submission(s): 3866

Problem Description
还记得Gardon给小希布置的那个作业么?(上次比赛的1005)其实小希已经找回了原来的那张数表,现在她想确认一下她的答案是否正确,但是整个的答案是很庞大的表,小希只想让你把答案中最大的M个数告诉她就可以了。
给定一个包含N(N<=3000)个正整数的序列,每个数不超过5000,对它们两两相加得到的N*(N-1)/2个和,求出其中前M大的数(M<=1000)并按从大到小的顺序排列。
 

Input
输入可能包含多组数据,其中每组数据包括两行:
第一行两个数N和M,
第二行N个数,表示该序列。

 

Output
对于输入的每组数据,输出M个数,表示结果。输出应当按照从大到小的顺序排列。
 

Sample Input
4 41 2 3 44 55 3 6 4
 

Sample Output
7 6 5 511 10 9 9 8

思路:哈希表的优势是以空间换取时间,哈希表又成散列表,因为它不一定是连续的,所以空间可能会占用很多,但是由于一般是可以直接找到,所以时间复杂度相对较低,适合要求运行时间少,内存可以消耗较多的情况。下面为本题代码:

#include<iostream>#include<cstring>#include<algorithm>#include<cstdio>using namespace std;const int maxn = 5000000;const int Max = 3001;int a[Max];int Hash[maxn];int cmp(int x,int y){    return x > y;}void cal(int m){    int i,j;    for(i=0;i<m-1;i++)    {        for(j=i+1;j<m;j++)        {            Hash[a[i] + a[j]]++;    //哈希表的运用            //cout<<a[i] + a[j]<<endl;        }    }}void display(int n,int sum){    int cnt = sum;    while(n && cnt)    {        if(Hash[cnt])        {            if(n > 1)                cout<<cnt<<" ";            else                cout<<cnt;            n--;            Hash[cnt]--;        }        else        {            cnt--;        }    }    cout<<endl;}int main(){    int m,n,i,sum;    //freopen("1.in","r",stdin);    while(cin>>m>>n)    {        memset(a,0,sizeof(a));        memset(Hash,0,sizeof(Hash));        for(i=0;i<m;i++)        {            cin>>a[i];        }        sort(a,a+m,cmp);        sum = a[0] + a[1];        cal(m);        display(n,sum);    }}

0 0
原创粉丝点击