#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
#define HASH 359987
typedef struct node
{
char str[22];
int key;
struct node *next;
};
node *h[HASH];
int hashcode(char str[])
{
int hash=0;
int len = strlen(str);
for(int i=0;i<len;i++)
hash =(31*hash+str[i])%HASH;
return hash;
}
void create(char str[],int x)
{
int hash = hashcode(str);
node *tmp =new node;
tmp->key=x;
strcpy(tmp->str,str);
tmp->next=h[hash];
h[hash]=tmp;
return ;
}
int find(char str[])
{
int hash = hashcode(str);
node *tmp = h[hash];
while(tmp!=NULL)
{
// printf("%s\n",tmp->str);
if(strcmp(tmp->str,str)==0)
return tmp->key;
tmp=tmp->next;
}
return -1;
}
int main()
{
int n,m,i,x;
char str[22];
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(h,0,sizeof(h));
for(i=0;i<n;i++)
{
scanf("%s %d",&str,&x);
create(str,x);
}
while(m--)
{
scanf("%s",&str);
printf("%d\n",find(str));
}
}
return 0;
}
/*
20 10
IG 3500
WE 4000
Fnatic 3900
GG 3950
EG 3700
SK 3750
TSM 3750
VUL 3850
CLG 3800
TPA 3700
PE 3600
HZ 3500
froggen 2300
alex 2161
kid 2132
weixiao 2382
WEcm 2310
IGpdd 2131
fzzf 2344
xiaoxiao 2012
IG
WE
SK
HZ
fzzf
froggen
alex
WE
qq
WEcm
*/
本文介绍了一种基于哈希表的数据结构实现方法,并通过示例代码详细解释了如何使用哈希表进行数据的存储与查找操作。文章还提供了一个具体的实例来演示哈希表的应用场景。
10万+

被折叠的 条评论
为什么被折叠?



