• poj 1056 IMMEDIATE DECODABILITY 字典树


    题目链接:http://poj.org/problem?id=1056

    思路:

    字典树的简单应用,就是判断当前所有的单词中有木有一个是另一个的前缀,直接套用模板再在Tire定义中加一个bool类型的变量用来判断当前到达的位置是否构成另一个单词的编码

    代码:

     1 #include<cstdio>
     2 #include<cstdlib>
     3 #include<iostream>
     4 #include<algorithm>
     5 #include<cstring>
     6 using namespace std;
     7 const int MAX=2;
     8 class Trie
     9 {
    10     public:
    11     bool isCode;
    12     Trie *next[MAX];
    13 };
    14 bool flag;
    15  
    16 void Build_Tree(Trie *root,char *str)
    17 {
    18     Trie *p=root;
    19     int i=0;
    20     while(str[i]!='')
    21     {
    22         if(p->next[str[i]-'0']==NULL)
    23         {
    24             Trie *temp=new Trie;
    25             for(int j=0;j<MAX;j++)
    26               temp->next[j]=NULL;
    27             temp->isCode=false;
    28             p->next[str[i]-'0']=temp;
    29         }
    30         else
    31         {
    32             if(p->next[str[i]-'0']->isCode)
    33             {
    34                 flag=false;
    35                 return;
    36             }
    37         }
    38         p=p->next[str[i]-'0'];
    39         i++;
    40     }
    41     p->isCode=true;
    42  
    43 }
    44 void del(Trie *root)
    45 {
    46     for(int i=0;i<MAX;i++)
    47       if(root->next[i]!=NULL)
    48         del(root->next[i]);
    49     free(root);
    50 }
    51 int main()
    52 {
    53     char str[20];
    54     int Case=0;
    55     while(scanf("%s",str)!=EOF)
    56     {
    57         Case++;
    58         Trie *root=new Trie;
    59         for(int i=0;i<MAX;i++)
    60             root->next[i]=NULL;
    61         root->isCode=false;
    62         flag=true;
    63         Build_Tree(root,str);
    64         while(scanf("%s",str))
    65         {
    66             if(strcmp(str,"9")==0)break;
    67             if(flag) Build_Tree(root,str);
    68         }
    69         if(flag)cout<<"Set "<<Case<<" is immediately decodable"<<endl;
    70         else cout<<"Set "<<Case<<" is not immediately decodable"<<endl;
    71         del(root);
    72     }
    73     return 0;
    74 }
    View Code
  • 相关阅读:
    CF1359D Yet Another Yet Another Task
    【数据结构】fhq_treap
    AtCoder Beginner Contest 182 题解
    UVA11992 Fast Matrix Operations
    双指针例题
    python使用国内镜像库
    APP元素定位工具之——Weditor
    安卓ADB的常见命令的使用
    函数进阶之迭代器,递归
    函数基础之对象,嵌套,名称空间和作用域
  • 原文地址:https://www.cnblogs.com/xiaozhuyang/p/poj1056.html
Copyright © 2020-2023  润新知