PKU-2503-Babelfish(哈希求解)

一般来说,超过10w的数组大小,若涉及到查找操作时,第一要考虑的数据结构是散列表,毕竟在散列表的支持下,查找操作所需的时间为O(1)。本题就是利用散列表解决问题的典型体现。另外针对字符串的哈希值我们考虑用unix的ELF哈希函数给输入字符串生产哈希值。

由于操作的对象是字符串,因此针对对象冲突问题,利用链表来解决是再合适不过了。

注:本题的输入情况比较特殊,字典输入和foreign language输入之间有个空行,所以考虑用gets函数输入字典后用sscanf函数提取English word和foreign word。

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define COLUMN 100000
#define LEN 11

//char dic[COLUMN][LEN];
struct node{
char s[LEN];
char sHash[LEN];
struct node* next;
}hashNode[COLUMN];

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);
}

void insert(char str[], char sHash[])
{
int h = ELFHash(sHash)%COLUMN;
struct node* p = &hashNode[h];
while (p->next != NULL){
p = p->next;
}
strcpy(p->s, str);
strcpy(p->sHash, sHash);
struct node* tmp = (struct node*)malloc(sizeof(struct node));
tmp->next = NULL;
p->next = tmp;
}

char* search(char sHash[])
{
int h = ELFHash(sHash)%COLUMN;
struct node* p = &hashNode[h];
while (p->next != NULL){
if (!strcmp(sHash, p->sHash))
return p->s;
p = p->next;
}
return NULL;
}

int main(void)
{
char s1[LEN], s2[LEN];
char buff[50];
memset(hashNode, 0, sizeof(hashNode));
while (gets(buff) && strcmp(buff, "") != 0){
sscanf(buff, "%s%s", s1, s2);
insert(s1, s2);
}

while (scanf("%s", s1) != EOF){
char* p = search(s1);
if (p)
printf("%s\n", p);
else
printf("eh\n");
}
return 0;
}



posted @ 2011-12-07 23:20  liftBug  阅读(367)  评论(0编辑  收藏  举报