POJ2503-Babelfish(ELFhash)

大致题意:

输入一个字典,字典格式为“英语à外语”的一一映射关系

然后输入若干个外语单词,输出他们的 英语翻译单词,如果字典中不存在这个单词,则输出“eh”

思路:

题目很简单,其实用map做更简单,只是想试一下ELFhash模板才做的。这题里有一点需要注意,也是我一开始没想到的。一开始还觉得ELFhash是一种看人品的算法,而且需要空间很大,来避免两个字符串撞车。后来发现其实还有一个类似与图论中一个类似于边表示的数据结构来解决撞车问题

上代码:

#include<cstdio>
#include<cstring>
#define N 100009
using namespace std;
struct node
{
	char s1[20],s2[20];
	int next;  
} p[N];
int head[N],cnt;
/*******可做模板*************************/ 
int ELFhash(char *key){  
    unsigned long h = 0;  
    unsigned long x = 0;  
    while (*key)  
    {  
        h = (h << 4) + (*key++);  
        if ((x = h & 0xF0000000L) != 0)  
        { 
            h ^= (x >> 24);  
            h &= ~x;  
        }  
    }  
    return h % N;  
}  
void addhash(int t,char s1[],char s2[])
{
	strcpy(p[cnt].s1,s1);
	strcpy(p[cnt].s2,s2);
	p[cnt].next=head[t];
	head[t]=cnt++;
}
int main()
{
	//FILE *fp=fopen("t.txt","r");
	int flag=1;
	char ans[20],s1[20],s2[20],s[100];
	memset(head,-1,sizeof(head));
	cnt=0;
	while(gets(s))
	{
		if(strlen(s)==0) 
		{
			flag=0;
			continue;
		}
		if(flag)
		{
			int t;
			sscanf(s,"%s%s",s2,s1);
			t=ELFhash(s1);
			addhash(t,s1,s2);
		}else
		{
			int t=ELFhash(s);
			char f=0;
			for(int i=head[t];i!=-1;i=p[i].next)
			{
				if(strcmp(p[i].s1,s)==0)
				{
					f=1;
					strcpy(ans,p[i].s2);
					break;
				}
			}
			if(f) printf("%s\n",ans);
			else printf("eh\n");
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值