【模板】字典树

 
#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 main()
{
    char ch[12],*t;
    Node *p,*root=createTrie(); 
    while(gets(ch)!=NULL)       //每次查询的字符串前缀 
    {
        int s=0;
        p=root;
        t=ch;
        while(*t!='\0')
        {
            if(p->next[*t-'a']==NULL)
            {
                s=0;
                break;
            }
            p=p->next[*t-'a'];
            s=p->sum;
            t++;
        }
        cout<<s<<endl;         //输出该前缀的单词数量 
    }
    return 0;
}
字典树详解!不理解就ClickHere!!

猜你喜欢

转载自www.cnblogs.com/kannyi/p/9114011.html