Immediate Decodability
http://acm.hdu.edu.cn/showproblem.php?pid=1305
同上题一样,判断一个串是不是另一个串的子串,用的是模拟二叉树
View Code
1 #include<stdio.h> 2 struct trie 3 { 4 int num; 5 trie *child[2]; 6 trie() 7 { 8 for(int i=0;i<2;i++) child[i]=0; 9 num=0; 10 } 11 } *root; 12 int flag; 13 void Insert(char *x) 14 { 15 int k=0; 16 trie *p=root; 17 while(x[k]!='\0') 18 { 19 if(p->child[x[k]-'0']==0) 20 p->child[x[k]-'0']=new trie; 21 p=p->child[x[k]-'0']; 22 if(p->num==2) 23 { 24 flag=1; 25 k++; 26 continue; 27 } 28 if(p->num==1) 29 { 30 if(x[k+1]=='\0') 31 flag=1; 32 k++; 33 continue; 34 } 35 p->num=1; 36 k++; 37 } 38 p->num=2; 39 } 40 void Free(trie *p) 41 { 42 for(int i=0;i<2;i++) 43 if(p->child[i]) 44 Free(p->child[i]); 45 delete p; 46 } 47 int main() 48 { 49 char x[10]; 50 int t=1; 51 root=new trie; 52 flag=0; 53 while(scanf("%s",x)!=EOF) 54 { 55 if(x[0]=='9') 56 { 57 if(flag) printf("Set %d is not immediately decodable\n",t++); 58 else printf("Set %d is immediately decodable\n",t++); 59 flag=0; 60 Free(root); 61 root=new trie; 62 continue; 63 } 64 Insert(x); 65 } 66 return 0; 67 }
http://www.doc88.com/p-898241392982.html字典树做法,动态的
View Code
1 #include<stdio.h> 2 #include<string.h> 3 #include<malloc.h> 4 bool isphone ; 5 struct node 6 { 7 bool flag ; 8 struct node *next[10] ; 9 } ; 10 struct node *root ; 11 struct node*creat() 12 { 13 node *p = (node*)malloc(sizeof(node)) ; 14 for(int i=0; i<10; i++) 15 { 16 p->next[i] = NULL ; 17 } 18 p->flag = false ; 19 return p ; 20 } 21 int insert(char *s) 22 { 23 node *p = root ; 24 int len = strlen(s) ; 25 for(int i=0; i<len; i++) 26 { 27 if(p->next[s[i]-'0']==NULL) 28 { 29 if(p->flag==false) 30 { 31 p->next[s[i]-'0'] = creat() ; 32 p = p->next[s[i]-'0'] ; 33 if(i==len-1) 34 { 35 p->flag = true ; 36 } 37 else 38 p->flag = false ; 39 } 40 else 41 { 42 isphone = false ; 43 return 0 ; 44 } 45 } 46 else 47 { 48 if(i==len-1&&p->flag==false) 49 { 50 isphone = false ; 51 return 0 ; 52 } 53 p = p->next[s[i]-'0'] ; 54 } 55 } 56 return 0 ; 57 } 58 int del(node *p) 59 { 60 if(p==NULL) 61 return 0 ; 62 for(int i=0; i< 10; i++) 63 { 64 if(p->next[i]!=NULL) 65 del(p->next[i]) ; 66 } 67 free(p) ; 68 return 0 ; 69 } 70 int main() 71 { 72 int num = 1 ; 73 char s[1010] ; 74 while(scanf("%s", s)) 75 { 76 root = creat() ; 77 isphone = true ; 78 insert(s) ; 79 while(scanf("%s", s),*s!='9') 80 { 81 insert(s) ; 82 } 83 if(isphone) 84 printf("Set %d is immediately decodable\n", num++) ; 85 else printf("Set %d is not immediately decodable\n", num++) ; 86 } 87 return 0 ; 88 }
结果Output Limit Exceeded