POJ 2503 Babelfish (Hash)

题意很好懂.就是给一个字典. 一个英文单词对应一个其他语言的单词.

然后给询问其他语言,要你给出对应的英文单词.

由于字典量高达100000.询问量也达到了100000. 所以用普通的遍历必定会超时.

网上给出的几种解决方案有

    1.先排序再二分查找.

    2.字典树

    3.哈希表

我用的是哈希表,采用ELFHash函数,用拉连法解决冲突.

因为函数关系.不同文本得到的哈希值也有可能相同,这时候我们就通过及时相同那么也把两个不同的文本放着同一个位置,

通过链表连接起来.  当我们在查询的时候.发现一样的哈希值有多个文本.那么只需要把这几个文本都小小的遍历一下就

可以了.

#include<iostream>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include<cstdio>
#include<limits.h>
using namespace std;
unsigned int Str_Hash(char *str);
 
struct Entry
{
	char english[12];
	char others[12];
	int next;
};
 
int Hash[100000];
Entry Dic [100000];
int cnt=0;
int main()
{
 
	memset(Hash,-1,sizeof(Hash));
	char data[25];
	int hash_value;
 
	while (gets(data))
	{
		if (data[0]==0)
			break;
		sscanf(data,"%s %s",Dic[cnt].english,Dic[cnt].others);
 
		hash_value=Str_Hash(Dic[cnt].others);
		Dic[cnt].next=Hash[hash_value];
		Hash[hash_value]=cnt;
 
		cnt++;
	}
 
	a:
	while (gets(data))
	{
		hash_value=	Str_Hash(data);	
		int i=Hash[hash_value];
		for (;i!=-1;i=i=Dic[i].next)
		{
			if (strcmp(data,Dic[i].others)==0)
			{
				printf("%s\n",Dic[i].english);
				goto a;
			}			
		}
		printf("eh\n");
	}
	return 0;
}
 
unsigned int Str_Hash(char *str)
{
    unsigned long h=0;
    while(*str)
    {
        h=(h<<4)+(*str++);
        unsigned long g=h&0Xf0000000L;
        if(g) h^=g>>24;
        h&=~g;
    }
    return h%100000;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值