pku 2503 Babelfish 哈希
http://poj.org/problem?id=2503
很简单的一个哈希,本来想求和然后模一个数哈希呢,提交果断tle。。。郁闷。最后看了看别人的哈希,在处理的时候好像用到了经典的unix的ELF哈希函数给输入字符串生产哈希值.我直接套的这个函数,提交就A了。。。
unix的ELF哈希函数
View Code
unsigned int ELFHash(char* str)
{
unsigned int hash = 0;
unsigned int x = 0;
while (*str){
hash = (hash << 4) + (*str++);
if ((x = hash & 0xF0000000L) != 0){
hash ^= (x >> 24);
hash &= ~x;
}
}
return (hash & 0x7FFFFFFF);
}
View Code
#include <iostream>
#include <cstring>
#include <cstdio>
#define maxn 100007
using namespace std;
struct node
{
char str1[12];
char str2[12];
node *next;
}*p[maxn],H[maxn];
int pos;
unsigned int ELFHash(char* str)
{
unsigned int hash = 0;
unsigned int x = 0;
while (*str){
hash = (hash << 4) + (*str++);
if ((x = hash & 0xF0000000L) != 0){
hash ^= (x >> 24);
hash &= ~x;
}
}
return (hash & 0x7FFFFFFF);
}
int main()
{
int i,tmp;
char s1[12],s2[12];
char s[24];
pos = 0;
memset(p,0,sizeof(p));
while (gets(s) != NULL && s[0] != '\0')
{
tmp = 0;
int len = strlen(s);
for (i = 0; i < len; ++i)
{
if (s[i] != ' ')
s1[i] = s[i];
else
break;
}
s1[i++] = '\0';
int k = 0;
for (; i < len; ++i)
s2[k++] = s[i];
s2[k] = '\0';
tmp = ELFHash(s2)%maxn;
node *t = &H[pos++];
strcpy(t->str1,s1);
strcpy(t->str2,s2);
t->next = p[tmp];
p[tmp] = t;
}
while (~scanf("%s",s1))
{
tmp = 0;
tmp = ELFHash(s1)%maxn;
node *q; bool flag = false;
for (q = p[tmp]; q != NULL; q = q->next)
{
if (!strcmp(q->str2,s1))
{
printf("%s\n",q->str1);
flag = true;
break;
}
}
if (!flag) printf("eh\n");
}
return 0;
}