字符串哈希函数。
思路:采用ELFhash函数,即(它用于UNIX的“可执行链接格式,ELF”中,这里把它写成C函数),见《算法艺术与信息学奥赛》P96
CODE:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 149993
typedef unsigned int UL;
int first[MAXN], cnt;
struct node
{
char s1[11], s2[11];
int next;
}a[MAXN];
int ELHhash(char *key)
{
UL h = 0;
while(*key)
{
h = (h<<4) + *key++;
UL g = h & 0xf0000000L;
if(g) h ^= g>>24;
h &= ~g;
}
return h%MAXN;
}
void insert(char *s, int cnt)
{
int h = ELHhash(s);
a[cnt].next = first[h];
first[h] = cnt;
}
void find(char *s)
{
int h = ELHhash(s);
for(int v = first[h]; v != -1; v = a[v].next)
{
if(strcmp(s, a[v].s2) == 0)
{
printf("%s\n", a[v].s1);
return ;
}
}
printf("eh\n");
}
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
int main()
{
char str[22];
init();
while(gets(str))
{
if(str[0] == '\0') break;
sscanf(str, "%s %s", a[cnt].s1, a[cnt].s2);
insert(a[cnt].s2, cnt);
cnt++;
}
while(gets(str))
{
find(str);
}
return 0;
}
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
#define MAXN 149993
typedef unsigned int UL;
int first[MAXN], cnt;
struct node
{
char s1[11], s2[11];
int next;
}a[MAXN];
int ELHhash(char *key)
{
UL h = 0;
while(*key)
{
h = (h<<4) + *key++;
UL g = h & 0xf0000000L;
if(g) h ^= g>>24;
h &= ~g;
}
return h%MAXN;
}
void insert(char *s, int cnt)
{
int h = ELHhash(s);
a[cnt].next = first[h];
first[h] = cnt;
}
void find(char *s)
{
int h = ELHhash(s);
for(int v = first[h]; v != -1; v = a[v].next)
{
if(strcmp(s, a[v].s2) == 0)
{
printf("%s\n", a[v].s1);
return ;
}
}
printf("eh\n");
}
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
int main()
{
char str[22];
init();
while(gets(str))
{
if(str[0] == '\0') break;
sscanf(str, "%s %s", a[cnt].s1, a[cnt].s2);
insert(a[cnt].s2, cnt);
cnt++;
}
while(gets(str))
{
find(str);
}
return 0;
}