zoukankan      html  css  js  c++  java
  • HDU1251 字典树 这题亮点在于是我自己写的字典树

      然后还翻看了之前AC的,一看,原来之前是用别人的模板来AC的,好无耻啊,这把是自己写的。

     1 /*
     2 自己来写字典树
     3 */
     4 #include <stdio.h>
     5 #include <malloc.h>
     6 #include <string.h>
     7 struct node
     8 {
     9     int size;                       //该结点上的前缀单词的个数
    10     struct node *child[26];         //下一个单词的结点
    11 }a;
    12 typedef struct node NODE;
    13 NODE *root;                        //表示根节点。(根节点里面什么也不包含)
    14 void insert(char word[])
    15 {
    16     int l=strlen(word);
    17     int i,j;
    18     int temp;
    19     NODE *s=root;
    20     for(i=0;i<l;++i)
    21     {
    22         temp=word[i]-'a';
    23         if(s->child[temp]==NULL)    //如果未出现,则建立一个。
    24         {
    25             NODE *t=(NODE *)malloc(sizeof(a));
    26             s->child[temp]=t;
    27             t->size=1;
    28             for(j=0;j<26;++j)
    29             {
    30                 t->child[j]=NULL;
    31             }
    32             s=t;                    //更换结点
    33         }
    34         else                        //如果出现了,则
    35         {
    36             s=s->child[temp];
    37             s->size++;
    38         }
    39     }
    40     return ;
    41 }
    42 void init(NODE *tem)               //重定义字典树
    43 {
    44     int i;
    45     for(i=0;i<26;++i)
    46     {
    47         if(tem->child[i]!=NULL)    //如果子节点不为空
    48         {
    49             init(tem->child[i]);
    50             free(tem->child[i]);
    51         }
    52     }
    53     return ;
    54 }
    55 int check(char word[])              //字符串的查找
    56 {
    57     int l=strlen(word);             //计算字符串的长度
    58     int i;
    59     int temp;
    60     int res;
    61     NODE *p=root;
    62     for(i=0;i<l;++i)
    63     {
    64         temp=word[i]-'a';
    65         if(p->child[temp]!=NULL)
    66         {
    67             p=p->child[temp];
    68             res=p->size;
    69         }
    70         else
    71         {
    72             return 0;
    73         }
    74     }
    75     return res;
    76 }
    77 int main()
    78 {
    79     char temp[15];
    80     int res;
    81     int i;
    82     root=(NODE *)malloc(sizeof(a));
    83     for(i=0;i<26;++i)
    84     {
    85         root->child[i]=NULL;
    86     }
    87     while(gets(temp),strcmp(temp,""))
    88     {
    89         insert(temp);
    90     }
    91     while(~scanf("%s",temp))
    92     {
    93         res=check(temp);
    94         printf("%d\n",res);
    95     }
    96     return 0;
    97 }
  • 相关阅读:
    创建可管理的对象属性
    解析简单xml文档
    定义类的__slots__属性节省内存的开销
    读写json数据
    读写csv,excel文件数据
    常用的字符串处理方法
    sql中case when 的使用
    对字典的处理
    元组的元素命名
    列表,字典,集合按条件筛选
  • 原文地址:https://www.cnblogs.com/symons1992/p/2940224.html
Copyright © 2011-2022 走看看