hdu 1075 What Are You Talking About trie字典树
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1075
大意:有外星人来了,但是我不懂外星文。然后我有一本字典,然我去翻译,字典由start开始有end结束的相当于map转换,然后是由由start开始有end结束的需要翻译的句子。
代码
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> typedef struct node { int flag; char ans[55]; struct node *next[27]; }tree; tree *new_node() { tree *p; p = (tree*)malloc(sizeof(tree)); int i; for(i = 0;i < 26;i++) p->next[i] = NULL; p->flag = 0; return p; } void insert(tree *rt,char s[],char ans[]) { tree *p; p = rt; int i; for(i = 0;s[i] != '\0';i++) { int t; t = s[i]-'a'; if(p->next[t] == NULL) p->next[t] = new_node(); p = p->next[t]; } strcpy(p->ans,ans); p->flag = 1; return; } int search(tree *rt,char s[]) { tree *p; p = rt; int i; for(i = 0;s[i] != '\0';i++) { int t; t = s[i]-'a'; if(p->next[t] == NULL) return 0; p = p->next[t]; } if(p->flag) { printf("%s",p->ans); return 1; } else return 0; } int main() { char s1[3005],s2[3000],word[3000]; int n,m,i,j,leap; tree *rt; scanf("%s",s1); rt = new_node(); while(~scanf("%s",s1)) { if(strcmp(s1,"END") == 0) break; scanf("%s",s2); insert(rt,s2,s1); } scanf("%s",s1); getchar(); while(gets(s2) != NULL) { if(strcmp(s2,"END") == 0) break; int count = 0,i; int len = strlen(s2); for(i = 0;i <= len;i++)//不能是< len,因为当输入sdad最后没有空格的时候他不会翻译。 { if(isalpha(s2[i])) word[count++] = s2[i]; else { word[count] = '\0'; if(count) { leap = search(rt,word); if(!leap) printf("%s",word); } if(i != len)//这里别忘了判断~ printf("%c",s2[i]); count = 0; } } puts(""); } return 0; }