zoukankan      html  css  js  c++  java
  • 字典树【模板】

    字典树:也是trie树,根节点不包含字符,除了根节点外每个节点包含一个字符,而且都不一样。从根结点单到某结点的连线就是所对应的字符串。可以查找,插入和删除。
    实现过程:从根节点开始,查找第一个单词,找到后再找相应的子树进行循环这个过程...

    模板如下:

    struct node
    {
        int cnt;     //记录该字符出现次数
         node *next[27];
    }*root;   //root根节点 
    void Maketree(char *str)     /*插入*/
    {
        int ans, i, len;
        node *p, *q;
        p=root; 
        len=strlen(str); 
        for(i=0; i<len; i++)
        {
            ans=str[i]-'a';
            if(p->next[ans]!=NULL)
            {
                p=p->next[ans];    //p指向父母结点 
                p->cnt++;
            }
            else
            {
                q=(node *)calloc(1, sizeof(node));    //创建新节点 
                p->next[ans]=q;    //q给该节点 
                p=q;    //p指向该节点 
                p->cnt=1;
            }
        }
    }
    void Findtree(char *str)     /*查找*/
    {
         int i, len, ans;
         node *p;
         p=root; 
         len=strlen(str); 
         for(i=0; i<len; i++)
         {
               ans=str[i]-'a';
             p=p->next[ans];
             printf("%c", str[i]);
             if(p->cnt==1)
                 break; 
         }
         printf("\n");
    }
  • 相关阅读:
    bzoj 4012: [HNOI2015]开店
    POJ 1054 The Troublesome Frog
    POJ 3171 Cleaning Shifts
    POJ 3411 Paid Roads
    POJ 3045 Cow Acrobats
    POJ 1742 Coins
    POJ 3181 Dollar Dayz
    POJ 3040 Allowance
    POJ 3666 Making the Grade
    洛谷 P3657 [USACO17FEB]Why Did the Cow Cross the Road II P
  • 原文地址:https://www.cnblogs.com/Hilda/p/2635836.html
Copyright © 2011-2022 走看看