动态字典树

it2022-05-07  3

 

#include <stdio.h> #include <string.h> #define M 3002 #define MU 26 #define WLEN 12 struct node{ char to[WLEN]; node *child[MU]; node() { to[0] = '\0'; memset(child,NULL,sizeof(child)); } }; char getTr[M],findEd[WLEN]; void clear(node *root) { for(int i=0;i<MU;i++) { if(root->child[i] != NULL) clear(root->child[i]); } delete root; } void insert(node *root, char *str, char *to) { node *p = root; int len = strlen(str); for(int i=0; i<len; i++) { int k = str[i] - 'a'; if(p->child[k] == NULL) { p->child[k] = new node; } p = p->child[k]; } strcpy(p->to,to); } void find(node *root, char *str) { node *p = root; int len = strlen(str); for(int i=0; i<len; i++) { int k = str[i] - 'a'; if(p->child[k] == NULL) return ; p = p->child[k]; } strcpy(findEd,p->to); } bool isChar(char ch) { if(ch >= 'a' && ch <= 'z') return true; return false; } void run() { node *root = new node; char s1[WLEN],s2[WLEN]; scanf("%s",s1); while(scanf("%s",s1)) { if(!strcmp(s1,"END")) break; scanf("%s",s2); insert(root,s2,s1); } scanf("%s",s1); getchar(); while(gets(getTr)) { if(!strcmp(getTr,"END")) break; int j = 0; int len = strlen(getTr); for(int i=0; i<len; i++) { if(isChar(getTr[i])) { s2[j++] = getTr[i]; } else { s2[j] = '\0'; findEd[0] = '\0'; find(root,s2); if(findEd[0] != '\0') printf("%s",findEd); else printf("%s",s2); printf("%c",getTr[i]); j = 0; } } printf("\n"); } clear(root); } int main(int argc, char *argv[]) { #ifdef __MYLOCAL freopen("in.txt","r",stdin); #endif run(); return 0; }

 

转载于:https://www.cnblogs.com/lk1993/p/3219513.html


最新回复(0)