ELFHash算法
一看就是個水題,很多方法可以解,最簡單的就應該是用map,但是出題的正解應該是使用ELFHash算法。
處理衝突,我們用拉鍊法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
#define MAXN 1000003
struct node
{
char m[11];
char s[11];
node *next;
};
node map[1000009];
int elf_hash(char *name)
{
int h = 0, g;
while (*name) {
h = (h << 4) + *name++;
if (g = h & 0xf0000000)
h ^= g >> 24;
h &= ~g;
}
return h%MAXN;
//return 5;
}
int main()
{
char s[22];
char s1[11],s2[11];
int l;
node *p;
node *t;
memset(map,0,sizeof(map));
while(gets(s)&&s[0]!=0)
{
sscanf(s,"%s %s",s1,s2);
// puts(s1);
// puts(s2);
l=elf_hash(s2);
p=&map[l];
if(p->m[0]!=0)
{
while(p->next!=NULL)
p=p->next;
t=new node;
t->next=NULL;
p->next=t;
p=t;
}
strcpy(p->m,s1);
strcpy(p->s,s2);
}
while(scanf("%s",s1)!=EOF)
{
l=elf_hash(s1);
// puts(s1);
p=&map[l];
while(p!=NULL)
{
if(strcmp(p->s,s1)==0)
{
puts(p->m);
break;
}
p=p->next;
}
if(p==NULL)
puts("eh");
// if(strcmp(p->s,s1)==0)
// {
// puts(p->m);
// }
// else
// puts("eh");
}
return 0;
}