初学字典树或想温习可以看:http://blog.csdn.net/chuck001002004/article/details/50421065
HDU 1075:http://acm.hdu.edu.cn/showproblem.php?pid=1075
题意:每个英文单词,否面都会有一个相应的火星文,输入一段火星文,要求转化为英文,未找到对应英文的的部分直接输出
分析:每录入一个火星文单词,在其结尾处不仅需要将end设为true,还需要附带一个对应的英文单词。翻译时还需要注意标点,空格等非26隔英文字母直接输出,未找到的单词也要直接输出
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
char a[3005],b[15];
typedef struct TrieNode
{
bool end;
struct TrieNode *next[26];
char word[15]; //每个火星文结尾要附带一个单词
}Trie;
Trie *root;
void init()//初始化函数
{
root=(Trie*)malloc(sizeof(Trie));
for(int i=0;i<26;i++)
root->next[i]=NULL;
root->end=false;
}
void Insert(char b[],char a[])
{
Trie *p=root;
int l=strlen(b);
for(int i=0;i<l;i++)
{
if(p->next[b[i]-'a']==NULL)
{
Trie *t=(Trie*)malloc(sizeof(Trie));
for(int j=0;j<26;j++)
t->next[j]=NULL;
t->end=false;
p->next[b[i]-'a']=t;
p=t;
}
else
{
p=p->next[b[i]-'a'];
}
}
p->end=true;
strcpy(p->word,a); //结尾将对应英文单词赋给word[]
}
int flag;
char ans[15];
void Search(char a[])
{
Trie *p=root;
int l=strlen(a);
for(int i=0;i<l;i++)
{
if(p->next[a[i]-'a']==NULL) //出现找不到的情况
{
flag=1;return ; //改变flag并返回
}
else
p=p->next[a[i]-'a'];
}
//检测结尾字母对应的是否也是火星文单词的结尾
if(p->end==false) flag=1; //不是则改变flag的值
else strcpy(ans,p->word); //否则将对应英文单词赋给ans[]
}
void DEL(Trie *root)
{
for(int i=0;i<26;i++)
if(root->next[i]!=NULL)
DEL(root->next[i]);
free(root);
}
int main()
{
scanf("%s",a);
init();
//此题输入就要用scanf,因为遇到空格或火车就会停止
while(scanf("%s",a)&&strcmp(a,"END")!=0)
{
scanf("%s",b);
Insert(b,a);
}
scanf("%s",a);
getchar();
while(gets(a)&&strcmp(a,"END")!=0)
{
int l=strlen(a);
int cnt=0;
for(int i=0;i<l;i++) //挨个录入字符串的字母
{
if(a[i]>='a'&&a[i]<='z')
b[cnt++]=a[i];
else //若遇到不是小写字母的时候
{
flag=0;
if(cnt) //若单词字母个数不为0则查找该单词
{
b[cnt]='\0';
Search(b);
if(flag) printf("%s",b); //flag为真说明未找到
else printf("%s",ans); //反之输出想对应的英文
}
cnt=0; //记得把cnt归零
if(a[i]) //如果此时的费字母的a[i]威震
printf("%c",a[i]); //则还要输出a[i]
}
}
printf("\n");
}
DEL(root);
return 0;
}