hdu1305-Immediate Decodability 字典树

字段树求前缀。

这里长短不一,只有存在前缀即可。

如果我们存下来排序会超时。

所以我们不能存下来。

如果已存的长,我们要找的短。那么我们只要遍历短的,如果短的全部都是已经存在的点。那么短的就是长的的内存。

如果已存的短,我们在短的最后一个字母处放一个flag,遍历长的,如果长的经历到这个点,发现这个点存在flag,说明短的是这个长的的前缀。

  1. #include <cstdio>  
  2. #include <cstring>  
  3. #include <cmath>  
  4. #include <algorithm>  
  5. #include <cstdlib>  
  6. using namespace std;  
  7. const int M=100005;  
  8. struct node  
  9. {  
  10.     int cnt;  
  11.     node *child[2];  
  12.     node()  
  13.     {  
  14.         cnt=0;  
  15.         for(int i=0; i<2; i++)  
  16.             child[i]=NULL;  
  17.     }  
  18. };  
  19. char a[15];  
  20. int flag;  
  21. node *root,*cur,*newnode;  
  22. void insert(char *a)  
  23. {  
  24.     cur=root;  
  25.     int len=strlen(a);  
  26.     for(int i=0; i<len ; i++)  
  27.     {  
  28.         int index=a[i]-'0';  
  29.         if(cur->child[index]!=NULL)  
  30.         {  
  31.             cur=cur->child[index];  
  32.             if(cur->cnt==1 || i==len-1)  
  33.             {  
  34.                 flag=0;//标记   
  35.                 break;  
  36.             }  
  37.         }  
  38.         else  
  39.         {  
  40.             newnode=new node;  
  41.             cur->child[index]=newnode;  
  42.             cur=newnode;  
  43.         }  
  44.     }  
  45.     cur->cnt=1;  
  46. }  
  47. void del(node *head)  
  48. {  
  49.     for(int i=0; i<2; i++)  
  50.         if(head->child[i]!=NULL)  
  51.             del(head->child[i]);  
  52.     delete(head);  
  53. }  
  54. int main()  
  55. {  
  56.     int g=1;  
  57.     while(scanf("%s",a)!=EOF)  
  58.     {  
  59.         flag=1;//标记默认为1   
  60.         root=new node;  
  61.         insert(a);  
  62.         while(scanf("%s",a)!=EOF)  
  63.         {  
  64.             if(strcmp(a,"9")==0)break;  
  65.             {  
  66.                 if(!flag)  
  67.                     continue;  
  68.                 insert(a);  
  69.             }  
  70.         }  
  71.         if(flag)printf("Set %d is immediately decodable\n",g++);  
  72.         else  
  73.             printf("Set %d is not immediately decodable\n",g++);  
  74.         del(root);  
  75.     }  
  76.     return 0;  
  77. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值