题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1075
题解:套字典树模版即可
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 50002
typedef struct node
{
struct node *child[26];//存储下一个字符
int cnt;//该节点是否是单词的结尾
char tranl[12];//翻译
}node,*Trie;
Trie root;//字典树的根节点
void insert(char *str,char *word)
{
int i,j,index,len;
Trie current,newnode;
len=strlen(str);
if(len==0)
return;//单词长度为0
current=root;//当前节点为根节点
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(current->child[index]!=NULL)//字典树存在该字符
{
current=current->child[index];
}
else
{
newnode=(struct node *)malloc(sizeof(struct node));//新增一节点
for(j=0;j<26;++j)
newnode->child[j]=NULL;
newnode->cnt=0;
strcpy(newnode->tranl,"");
current->child[index]=newnode;
current=newnode;//修改当前节点
}
}
current->cnt=1;//该节点是单词的尾
strcpy(current->tranl,word);
}
void query(char *str,char *word)
{
int i,index,len,ans;
Trie current;
len=strlen(str);
if(len==0)
{
strcpy(word,str);
return ;
}
current=root;//从根节点开始查找
for(i=0;i<len;++i)
{
index=str[i]-'a';
if(current->child[index]==NULL)
{
strcpy(word,str);
return;//字典树不存在此单词
}
else
{
current=current->child[index];
}
}
if(current->cnt==1)//字典树存在该单词
strcpy(word,current->tranl);
else
strcpy(word,str);
}
void Del(Trie root)//释放内存
{
int i;
if(root==NULL)
return;
for(i=0;i<26;++i)
{
if(root->child[i]!=NULL)
Del(root->child[i]);
}
free(root);
root=NULL;
}
int main()
{
int i,j;
char str1[12],str2[12],book[3002],temp[12];
root=(struct node *)malloc(sizeof(struct node));
for(i=0;i<26;++i)
root->child[i]=NULL;
root->cnt=0;
strcpy(root->tranl,"");
scanf("%s",str1);
while(scanf("%s",str1))
{
if(!strcmp(str1,"END"))
break;
scanf("%s",str2);
insert(str2,str1);
}
scanf("%s",str1);
getchar();
while(1)
{
gets(book);
if(!strcmp(book,"END"))
break;
for(i=0,j=0;book[i]!='\0';++i)
{
if(book[i]>='a'&&book[i]<='z')
temp[j++]=book[i];
else
{
temp[j]='\0';
query(temp,str2);
printf("%s",str2);
printf("%c",book[i]);//符号空格不需要翻译,所以直接输出.
j=0;
}
}
printf("\n");
}
Del(root);
return 0;
}