http://acm.hdu.edu.cn/showproblem.php?pid=1075
经过前两个字典树的学习运用,现在在它们的基础上做了这个题,其代码贴在下面,供我以后再回首时能想起。
//字典树
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _node
{
char english[12];
_node *next[26];
}node;
static node root = {"",NULL};
void insert(char *martian, int lenm, char *eng)
{
int i;
node *cur, *newnode;
cur = &root;
for(i = 0; i < lenm; i++){
if(cur->next[martian[i]-'a']==NULL){
newnode = (node*)malloc(sizeof(node));
memset(newnode, 0, sizeof(node));
newnode->english[0] = '\0';
cur->next[martian[i]-'a'] = newnode;
}
cur = cur->next[martian[i]-'a'];
}
strcpy(cur->english, eng);
}
node* find(char *martian, int lenm)
{
node * cur;
cur = &root;
int i;
for(i = 0; i < lenm; ++i){
if(cur->next[martian[i]-'a'] == NULL)return NULL;
cur = cur->next[martian[i]-'a'];
}
return cur;
}
int main()
{
// freopen("input.txt", "r", stdin);
char *martian, *english;
char test[3001];
int i,lenm;
martian = (char*)malloc(sizeof(char)*12);
english = (char*)malloc(sizeof(char)*12);
node *search;
while(scanf("%s", english)!=EOF){
if(strcmp(english, "START")==0)continue;
else if(strcmp(english, "END")==0)break;
else{
scanf("%s", martian);
lenm = strlen(martian);
insert(martian, lenm, english);
// printf("%s %s\n",martian, english);
}
}
scanf("%*c");
// search = find("fiwo", 4);
// printf("%s", search->english);
while(gets(test)){
if(strcmp(test, "START")==0)continue;
else if(strcmp(test, "END")==0)break;
else{
// printf("%s\n", test);
int lentest = strlen(test);
lenm = 0;
int f = 0;
for(i = 0; i < lentest; ++ i){
if(f == 0){
if(test[i]>='a'&&test[i]<='z'){
martian[lenm ++]=test[i];
}
else {
martian[lenm] = '\0';
search = find(martian, lenm);
if(search==NULL||search->english[0] == '\0'){
printf("%s", martian);
}
else {
printf("%s", search->english);
}
printf("%c", test[i]);
f = 1;
lenm = 0;
}
}
else if(f == 1){
if(test[i] <='z'&&test[i]>='a'){
f = 0;
martian[lenm ++] = test[i];
}
else printf("%c", test[i]);
}
}
printf("\n");
}
}
// printf("end\n");
return 0;
}