大致题意:
输入一个字典,字典格式为“英语à外语”的一一映射关系
然后输入若干个外语单词,输出他们的 英语翻译单词,如果字典中不存在这个单词,则输出“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;
}