poj-1056 IMMEDIATE DECODABILITY 字典树
最基础的字典树…插入一个串的时候,检查它的前缀是否已存在再检查它是否是前面给出的串的前缀…..
View Code
1 //poj 1056 Accepted 176K 0MS C++ 1012B 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 #define M 2 6 using namespace std; 7 int ii; 8 bool flag; 9 struct Tree{ 10 Tree* next[M]; 11 int val; 12 Tree() 13 { 14 for(ii=0;ii<M;ii++) 15 next[ii] = 0; 16 val = 0; 17 } 18 }; 19 20 void insert(Tree * root,char s[]) 21 { 22 int len,i,j; 23 Tree* p; 24 len = strlen(s); 25 p = root; 26 for(i=0;i<len;i++) 27 { 28 j = s[i] - '0'; 29 if(p->next[j]==0) 30 p->next[j] = new Tree; 31 p = p->next[j]; 32 if(p->val==1) flag = false; 33 } 34 p->val = 1; 35 for(i=0;i<10;i++) 36 if(p->next[i]) 37 flag = false; 38 } 39 40 41 void freedom(Tree *p) //释放空间 42 { 43 int i=0; 44 for(i=0;i<10;i++) 45 if(p->next[i]!=NULL) 46 freedom(p->next[i]); 47 free(p); 48 } 49 int main(void) 50 { 51 char str[100]; 52 int num=0; 53 flag = true; 54 Tree* root = new Tree; 55 while(scanf("%s",str)!=EOF) 56 { 57 if(str[0]!='9') 58 { 59 if(flag) 60 insert(root,str); 61 } 62 else 63 { 64 if(flag) 65 printf("Set %d is immediately decodable\n",++num); 66 else 67 printf("Set %d is not immediately decodable\n",++num); 68 freedom(root); 69 root = new Tree; 70 flag = true; 71 } 72 } 73 return 0; 74 }


浙公网安备 33010602011771号