字典樹的應用。
其實這個題可以用map很簡單的做出來,但字典樹在解決這種求解字符串匹配由於暴力求解而造成的超時的聞聽更爲明顯,所以更傾向這種方法。
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
struct Tree{
int next[26];
char english[12];
}cat[200004];
int temp;
char engl[12],fore[12];
void build(char *s,int site)
{
if(*s)
{
if(!cat[site].next[*s - 'a'])
cat[site].next[*s - 'a'] = ++ temp;
build(s + 1,cat[site].next[*s - 'a']);
}
else
strcpy(cat[site].english,engl);
}
void search(char *s,int site)
{
if(*s)
{
if(!cat[site].next[*s - 'a'])
{cout << "eh" << endl;return;}
search(s + 1,cat[site].next[*s - 'a']);
}
else
cout << cat[site].english << endl;
}
int main()
{
char str1[100];
while(gets(str1) && str1[0]){
sscanf(str1,"%s %s",engl,fore);
build(fore,0);
}
char str2[12];
while((scanf("%s",str2)) != EOF)
search(str2,0);
return 0;
}