Description
Input
Output
Sample Input
dog ogday cat atcay pig igpay froot ootfray loops oopslay atcay ittenkay oopslay
Sample Output
cat eh loops
Hint
这个题需要用到字典树,那么什么是字典树呢?
百度一下就可知道了------>地址是:Trie树
我比较喜欢用数组来写字典树,我在这放了两张图片!
希望能帮助理解!
本题题意:是要求我们将某一个星球的单词翻译成对应的英语,如果有就输出对应的英文,没有就不输出!
思路:这个题先得用某一个星球的单词来建立一个字典树,然后再将对应单词“放”在叶子节点后面,可以将其比喻为有坠子的耳环!然后在翻译时直接查找即可!
然后就是处理最开始的一段输入的问题了!
gets(str)是以‘\n’作为结束符的,另外,它也是可以读入回车符的,所以就用gets(str)作为输入,用两个for循环便可轻松的将英语单词和某球单词分开,此处就不作其它优化了!然后就可进行建树了!
AC代码如下:
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
const int maxn=201314;
struct Tree
{
int next[26];
char wei[26];//在对应的 树尾 上加一个尾巴!
void init()
{
memset(next,-1,sizeof(next));
}
} t[maxn];
int cur=1;
void creat(char ss[],int len,char ci[])
{
int p=0;
for(int i=0; i<len; i++)
{
int x=ss[i]-'a';
if(t[p].next[x]==-1)
{
t[cur].init();
t[p].next[x]=cur++;
}
p=t[p].next[x];
}
strcpy(t[p].wei,ci);
}
void cha(char ss[])
{
int p=0,i=0;
while(ss[i])
{
int x=ss[i]-'a';
if(t[p].next[x]==-1)
{
cout<<"eh"<<endl;
return ;
}
p=t[p].next[x];
i++;
}
cout<<t[p].wei<<endl;
}
int main()
{
t[0].init();//必须初始化!
char str1[2013],str2[2014];
while(gets(str1))
{
if(!strlen(str1))
break;
char qian[2013],hou[2014];
int p=0;
while(str1[p]!=' ')
{
qian[p]=str1[p];
p++;//把前面的单词提取出来!
}
qian[p]='\0';
int cnt=0;
for(int i=p+1; i<strlen(str1); i++)
hou[cnt++]=str1[i];//提取后面的单词!
hou[cnt]='\0';
creat(hou,strlen(hou),qian);
}
while(gets(str2)!=NULL)
cha(str2);
return 0;
}
原文地址:http://blog.csdn.net/u014004096/article/details/37936651