码迷,mamicode.com
首页 > 其他好文 > 详细

【模板】字典树

时间:2018-05-31 00:37:56      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:its   词汇   IV   pac   close   TE   isp   ret   字典   

技术分享图片
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
    int sum;
    Node*next[26];
}node;
void init(Node*node)
{
    node->sum=0;
    for(int i=0;i<26;i++)
        node->next[i]=NULL; 
}
Node*createTrie()
{
    char ch[12],*t;
    Node*root=new Node,*p;
    init(root); 
    while(gets(ch)&&strlen(ch))
    {
        if(ch[0]==\0)
            break;
        p=root;
        t=ch;
        while(*t!=\0)
        {
            if(p->next[*t-a]==NULL)
            {
                p->next[*t-a]=new Node;
                init(p->next[*t-a]);
            }
            p=p->next[*t-a];
            p->sum++;
            t++;
        }
    } 
    return root;
}
int Find(char*ch,Node*root)
{
    char*t=ch;
    Node*p=root;
    int s=0;
    while(*t!=\0)
    {
        if(p->next[*t-a]==NULL)
        {
            s=0;
            break;
        }
        p=p->next[*t-a];
        s=p->sum;
        t++;
    }
    return s;
} 
int main()
{
    char ch[12];
    Node*root=createTrie(); 
    while(gets(ch)!=NULL)
    {
        cout<<Find(ch,root)<<endl;
    }
    return 0;
}
字典树模板
技术分享图片
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
    int sum;       //子节点个数 
    Node*next[26]; //26个子节点 
}node;
void init(Node*node)
{
    node->sum=0;
    for(int i=0;i<26;i++)
        node->next[i]=NULL; 
}
Node*createTrie()
{
    char ch[12],*t;
    Node*root=new Node,*p;
    init(root); 
    while(gets(ch)&&strlen(ch))//获取每个词汇加入字典树 
    {
        if(ch[0]==\0)  //遇到空行,则结束建树
            break;
        p=root;          //当前节点
        t=ch;
        while(*t!=\0)  //每增加一个字符,都会使某个节点sum+1
        {
            if(p->next[*t-a]==NULL) //如果节点不存在,先创建 
            {
                p->next[*t-a]=new Node;
                init(p->next[*t-a]);
            }
            p=p->next[*t-a]; //当前节点进入树的下一层
            p->sum++;          //从根到当前节点的字符串为前缀的单词数增加了1个 
            t++;               //下一个字符 
        }
    } 
    return root;
}
int Find(char*ch,Node*root)
{
    char*t=ch;
    Node*p=root;
    int s=0;
    while(*t!=\0)
    {
        if(p->next[*t-a]==NULL)
        {
            s=0;
            break;
        }
        p=p->next[*t-a];
        s=p->sum;
        t++;
    }
    return s;
} 
int main()
{
    char ch[12];
    Node*root=createTrie(); 
    while(gets(ch)!=NULL)          //每次查询的字符串前缀
    {
        cout<<Find(ch,root)<<endl; //输出该前缀的单词数量
    }
    return 0;
}
字典树模板详解!不理解就ClickHere!!!

 

【模板】字典树

标签:its   词汇   IV   pac   close   TE   isp   ret   字典   

原文地址:https://www.cnblogs.com/kannyi/p/9114011.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!