您的位置:首页 > 理论基础 > 数据结构算法

poj 2503 Babelfish(字典树)

2015-04-18 19:49 435 查看
Babelfish

点击打开链接

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 35059Accepted: 15002
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.

题目:,就是每个字符串对应一个foreign字符串,然后给出foreign字符串,进行翻译、

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<map>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
struct node
{
char word[12];//比一般的树 多了一个,存储翻译后的词
int x;
node *next[26];
node()
{
x=0;
memset(word,0,sizeof(word));
memset(next,0,sizeof(next));
}
};
node *root=NULL;

void insert(char *s1,char *s2)
{
node *p=root;
int i;
for(i=0;i<strlen(s2);i++)
{
int k=s2[i]-'a';
if(p->next[k]==NULL)
p->next[k]=new node;
p=p->next[k];
}
p->x++;//此处是标记最后
strcpy(p->word,s1);//需要插入两个单词

}

void search(char *s)//查找很好懂
{
node *p=root;
int flag=1;
for(int i=0;i<strlen(s);i++)
{
int k=s[i]-'a';
if(p->next[k]==NULL)
{
printf("eh\n");
return ;
}
p=p->next[k];
}
printf("%s\n",p->word); //打印最后翻译的单词
}
char str1[35],str2[35],str[35];
int main()
{
root=new node;
char c;
while(~scanf("%s %s",str1,str2))
{
insert(str1,str2);
getchar();//读入回车
c=getchar();
if(c=='\n')  break;
ungetc(c,stdin);//如果c不是回车,则将c重新让回输入缓冲区。ungetc()函数。

}
while(~scanf("%s",str))
search(str);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息