Time Limit: 3000MS | Memory Limit: 65536KB | 64bit IO Format: %I64d & %I64u |
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.
Source
字典树的简单题,上次这个题是用map做的,这次用来熟悉一下字典树。代码如下:
//还是老办法,不懂的地方手动画个字典树看看就知道了
#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int maxn=200000+5;//结点数应该不会超过100000*2,不要问我为什么,我也不知道。也许可以证明一下???
int ch[maxn][26];//a~z对应0~25,势必有一些空间是浪费的,这就是字典树的特点之一:用空间换时间
char s[25],a[11],b[11];
char save[maxn][11];//维护一个save数组,存储单词结尾信息。如果save非空,说明是单词结尾
int tp;//结点编号
void insert(char *x,int site)
{
if(*x)//如果还没读到字符串的结尾
{
if(!ch[site][*x-'a'])//如果没有公共前缀(即前缀不存在或为空)
ch[site][*x-'a']=++tp;//建立新的结点(如果前缀存在,则不进行)
insert(x+1,ch[site][*x-'a']);
}
else strcpy(save[site],a);//在字符串末尾附加save数组,表示单词结尾
}
void query(char *x,int site)//查询按照插入的理解就可以
{
if(*x)
{
if(!ch[site][*x-'a'])
printf("eh\n");
else
query(x+1,ch[site][*x-'a']);
}
else
printf("%s\n",save[site]);
}
int main()
{
tp=0;
while(1)//记住这种读取字符串的处理方式
{
gets(s);
if(s[0]=='\n'||s[0]=='\0') break;
sscanf(s,"%s%s",a,b);
insert(b,0);
}
while(scanf("%s",a)!=EOF)
{
query(a,0);
}
return 0;
}
#include <iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
const int maxn=200000+5;//结点数应该不会超过100000*2,不要问我为什么,我也不知道。也许可以证明一下???
int ch[maxn][26];//a~z对应0~25,势必有一些空间是浪费的,这就是字典树的特点之一:用空间换时间
char s[25],a[11],b[11];
char save[maxn][11];//维护一个save数组,存储单词结尾信息。如果save非空,说明是单词结尾
int tp;//结点编号
void insert(char *x,int site)
{
if(*x)//如果还没读到字符串的结尾
{
if(!ch[site][*x-'a'])//如果没有公共前缀(即前缀不存在或为空)
ch[site][*x-'a']=++tp;//建立新的结点(如果前缀存在,则不进行)
insert(x+1,ch[site][*x-'a']);
}
else strcpy(save[site],a);//在字符串末尾附加save数组,表示单词结尾
}
void query(char *x,int site)//查询按照插入的理解就可以
{
if(*x)
{
if(!ch[site][*x-'a'])
printf("eh\n");
else
query(x+1,ch[site][*x-'a']);
}
else
printf("%s\n",save[site]);
}
int main()
{
tp=0;
while(1)//记住这种读取字符串的处理方式
{
gets(s);
if(s[0]=='\n'||s[0]=='\0') break;
sscanf(s,"%s%s",a,b);
insert(b,0);
}
while(scanf("%s",a)!=EOF)
{
query(a,0);
}
return 0;
}
总结:字典树开始还是有点难理解的,虽然好像没有线段树那么坑。。。这个可作为模板使用