动态字典树_前缀相互查找(HDU_1671)

/*

注意:

   911

   911123

这组数据可以得到正确的答案

   911123

   911

对于这组数据就判断失误了

用一个标记变量flag来标记插入过程中是否有重新创建节点

*/

#include <stdio.h> #include <string.h> #include <stdlib.h> #define M 10 struct node{ int end; node *child[M]; node() { end = 0; memset(child,NULL,sizeof(child)); } }; void clear(node *root) { for(int i=0;i<M;i++) { if(root->child[i] != NULL) clear(root->child[i]); } delete root; } int insert(node *root, char *str) { node *p = root, *newnode = NULL; int exist = 0, hasnew = 0, len = strlen(str); for(int i=0; i<len; i++) { int k = str[i] - '0'; if(p->child[k] != NULL) { p = p->child[k]; if(p->end) exist = 1; } else { p->child[k] = new node; p = p->child[k]; hasnew = 1; } } p->end = 1; if(exist || !hasnew) return 1; return 0; } int main(int argc, char* argv[]) { #ifdef __MYLOCAL freopen("in.txt","r",stdin); #endif int t,n,flag; char id[M + 2]; node *root; scanf("%d",&t); while(t--) { root = new node; flag = 0; scanf("%d",&n); while(n--) { scanf("%s",id); if(!flag) flag = insert(root,id); } if(flag) printf("NO\n"); else printf("YES\n"); clear(root); } return 0; }

 

posted on 2013-07-22 19:17  lk1993  阅读(153)  评论(0编辑  收藏  举报