大致题意:
输入一个字典,字典格式为“英语à外语”的一一映射关系
然后输入若干个外语单词,输出他们的 英语翻译单词,如果字典中不存在这个单词,则输出“eh”
解题思路:trie树
代码如下:
#include<iostream>
#include<cstring>
using namespace std;
const int Max = 260050;
const int branchNum = 26;
struct tree_node
{
char re[11]; // 存储对应的re串。
tree_node *next[branchNum];
}root, node[Max];
int p = 0;
void insert(char *word, char *re)
{
tree_node *location = &root;
while(*word)
{
if(location->next[*word-'a'] == NULL)
location->next[*word-'a'] = &node[p ++];
location = location->next[*word-'a'];
word ++;
}
strcpy(location->re, re);
}
void search(char *word)
{
tree_node *location = &root;
while(*word && location)
{
location = location->next[*word-'a'];
word ++;
}
if(location != NULL && location->re != 0)
printf("%s\n", location->re);
else
printf("eh\n");
}
int main()
{
char c, re[11], word[11];
while(1)
{
scanf("%s%s", re, word);
insert(word, re);
getchar(); // 读入回车。
c = getchar();
if(c == '\n')
break;
ungetc(c, stdin); // 如果c不是回车,则将c重新让回输入缓冲区。ungetc()函数。
}
while(scanf("%s", word) != EOF)
search(word);
return 0;
}