poj 2503 Babelfish
February 27, 2013
POJ
Data Structure
Babelfish Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 26498 Accepted: 11378
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
Hint Huge input and output,scanf and printf are recommended.
简单的字典树就可以做……
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
const int sonnum = 26, base = 'a';
struct Trie
{
int num; bool terminal; char dic[20];
Trie *son[sonnum];
};
Trie *NewTrie()
{
Trie *temp = new Trie;
temp->num = 1; temp->terminal = false;
memset(temp->dic, 0, sizeof(temp->dic));
for (int i = 0; i < sonnum; ++i) temp->son[i] = NULL;
return temp;
}
void Insert(Trie *pnt, char *s, int len, char *t)
{
Trie *temp = pnt;
for (int i = 0; i < len; ++i)
{
if (temp->son[s[i]-base] == NULL)
temp->son[s[i]-base] = NewTrie();
else temp->son[s[i]-base]->num++;
temp = temp->son[s[i]-base];
}
temp->terminal = true;
strcpy(temp->dic, t);
// temp->dic = t;
}
Trie *Find(Trie *pnt, char *s, int len)
{
Trie *temp = pnt;
for (int i = 0; i < len; ++i)
{
if (temp->son[s[i]-base] == NULL)
{
printf("eh\n");
return temp;
}
else temp = temp->son[s[i]-base];
}
if (temp->terminal == true)
printf("%s\n", temp->dic);
return temp;
}
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("poj2503.in", "r", stdin);
#endif
Trie *pnt = NewTrie();
char a[20], b[20], t;
while (1)
{
scanf("%s", a);
t = getchar();
if (t == '\n')
break;
scanf("%s", b);
Insert(pnt, b, strlen(b), a);
}
Find(pnt, a, strlen(a));
while (~scanf("%s", a))
{
Find(pnt, a, strlen(a));
}
return 0;
}
但是我有一个困惑,关于指针的。
如果把结构体中的dic换成指针形式,char *dic; 在Insert函数中写成 temp->dic = t; 但是程序结果为什么输出的是原来的单词,而不是翻译后的单词?
这个问题现在还没想明白,以后还得多花时间学学C语言啊……