Phone List題解(字典樹)
阿新 • • 發佈:2019-02-10
// 12 7 // by qiu // funtion trie #include <cstdio> #include <cstdlib> #include <malloc.h> #include <cstring> typedef struct node{ int val; struct node *next[10]; }tree; tree *build(){ tree *root=(tree*)malloc(sizeof(node)); root->val=1; for(int i=0; i<10; i++) root->next[i]=NULL; return root; } void insert_tree(tree *root, char *s){ int i=0; while(s[i]){ int k=s[i]-'0'; if(!root->next[k]) root->next[k]=build(); else root->next[k]->val++; root=root->next[k]; i++; } } int search_tree(tree *root, char *s){ int cnt=0, i=0; while(s[i]){ int k=s[i]-'0'; if(!root->next[k]) return 0; cnt=root->next[k]->val; root=root->next[k]; i++; } return cnt; } void Delete(tree *T){ if(T==NULL) return; for(int i=0; i<10; i++) if(T->next[i]!=NULL) Delete(T->next[i]); free(T); return ; } int main(){ int t, n, i; char s[10010][11]; scanf("%d", &t); while(t--){ scanf("%d", &n); tree *Root=build(); for(i=0; i<n; i++){ scanf("%s", s[i]); insert_tree(Root, s[i]); } for(i=0; i<n; i++){ if(search_tree(Root, s[i])>1) break; } if(i>=n) printf("YES\n"); else printf("NO\n"); Delete(Root); } return 0; }