B - Babelfish POJ - 2503
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
Hint
Huge input and output,scanf and printf are recommended.
解题思路
本题是字典树模板题,我的思路是记录下每行第二个"不认识"单词的cnt值,并把它和第一个单词匹配,并用数组第一维的下标存储
这样在下面第二次寻找这些"外国"单词的时候,使用开始存储的下标对应到数组中输出即可
注意,这里要使用scanf和printf,所以笔者使用了字符数组(不想处理string的scanf)
AC代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e6 + 10;
int son[N][11], vis[N], cnt;
char ans[N][15], scan[15], sca[15];
int insert()
{
int cur = 0;
for (int i = 0; scan[i]; i++)
{
int u = scan[i] - 'a';
if (!son[cur][u])
son[cur][u] = ++cnt;
cur = son[cur][u];
}
vis[cur] = 1;
return cur;
}
int query()
{
int cur = 0;
for (int i = 0; sca[i]; i++)
{
int u = sca[i] - 'a';
if (!son[cur][u])
return 0;
cur = son[cur][u];
}
return cur;
}
int main()
{
while (scanf("%s", sca) && sca[0] != '\0' && sca[0] != '\n')
{
scanf("%s", &scan);
int len = strlen(sca);
for (int i = 0; i < len; i++)
{
ans[insert()][i] = sca[i];
}
}
while (scanf("%s", &sca) != EOF)
{
if (!query())
{
printf("eh\n");
}
else
{
int len = strlen(ans[insert()]);
for (int i = 0; i < len; i++)
{
printf("%c", ans[insert()][i]);
}
puts("");
}
}
}