Description
You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language. Fortunately, you have a dictionary to help you understand them.
Input
Input consists of up to 100,000 dictionary entries, followed by a blank line, followed by a message of up to 100,000 words. Each dictionary entry is a line containing an English word, followed by a space and a foreign language word. No foreign word appears
more than once in the dictionary. The message is a sequence of words in the foreign language, one word on each line. Each word in the input is a sequence of at most 10 lowercase letters.
Output
Output is the message translated to English, one word per line. Foreign words not in the dictionary should be translated as "eh".
Sample Input
dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay
Sample Output
cat eh loops
解题思路:
这题用字典树做可以,用map映射做也可以。当然字典树效率比map高,但字典树代码复杂度肯定是远高于map了。
map提交:
字典树提交:
AC代码:
map:
#include <iostream>
#include <cstdio>
#include <map>
#include <cstring>
using namespace std;
int main()
{
map<string,string> dic;
char word_1[15], word_2[15], str[30];
while(gets(str) && str[0] != 0)
{
sscanf(str,"%s %s", word_1, word_2);
dic[word_2] = word_1;
}
while(scanf("%s", word_2) != EOF)
{
string ans = dic[word_2];
if(ans[0] != 0)
cout<< ans<<endl;
else
printf("eh\n");
}
return 0;
}
字典树:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
struct node{
char wrd[15];
node *next[26];
node(){
for(int i=0;i<26;i++)
next[i]=NULL;
}
};
node *root;
void Insert(char *str,char *wrd){
node *loc = root, *tmp;
for(int i = 0; str[i] != '\0'; i++)
{
int id = str[i] - 'a';
if(loc -> next[id] != NULL)
loc=loc->next[id];
else
{
tmp = new node;
loc -> next[id] = tmp;
loc = loc -> next[id];
}
}
strcpy(loc->wrd,wrd);
}
int SearchTrie(char *str, char *wrd)
{
node *loc = root;
for(int i = 0;str[i] != '\0'; i++)
{
int id = str[i]-'a';
if(loc -> next[id] != NULL)
loc = loc -> next[id];
else
return 0;
}
strcpy(wrd,loc -> wrd);
return 1;
}
int main()
{
root = new node;
char wrd[15], str[15];
char s[40];
while(gets(s))
{
if(strlen(s) == 0)
break;
sscanf(s,"%s%s", wrd, str);
Insert(str, wrd);
}
while(gets(str))
{
int flag = SearchTrie(str, wrd);
if(flag)
printf("%s\n",wrd);
else
printf("eh\n");
}
return 0;
}

本文介绍了一个翻译挑战问题,通过构建字典树或使用map进行词汇映射来实现从一种语言到另一种语言的转换。文章提供了两种方法的具体实现代码,包括基于map的简单实现和基于字典树的高效实现。

495

被折叠的 条评论
为什么被折叠?



