题目:传送门。
分析:串的哈希基础题,采用ELFhash算法。另外这道题很水,用c++STL里的map写就更方便了。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXN=1e5+5;
const int MOD=1e5+1;
int cnt;
int hash[MOD];
struct Dic{
char word1[12];
char word2[12];
int next;
}dic[MAXN];
int ELFhash(char *str){
unsigned long h = 0;
unsigned long x = 0;
while (*str){
h = (h << 4) + (*str++);
if ((x = h & 0xF0000000L) != 0){
h ^= (x >> 24);
h &= ~x;
}
}
return h % MOD;
}
void insert(char *word1,char *word2){
int key=ELFhash(word2);
strcpy(dic[cnt].word1,word1);
strcpy(dic[cnt].word2,word2);
dic[cnt].next=hash[key];
hash[key]=cnt++;
}
void trans(char *word){
int key=ELFhash(word);
for(int i=hash[key];i!=-1;i=dic[i].next){
if(strcmp(dic[i].word2,word)==0){
cout<<dic[i].word1<<endl;
return ;
}
}
cout<<"eh"<<endl;
}
int main(){
char word1[12],word2[12],word[12];
memset(hash,-1,sizeof hash); cnt=0;
while(true){
char s=getchar();
if(s=='\n') break;
word1[0]=s;
scanf("%s %s",&word1[1],word2);
insert(word1,word2);
getchar();
}
while(~scanf("%s",word)){
trans(word);
}
return 0;
}