Trie树入门

https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html  挺详细的

Trie树就是传说中的字典树啦  通过树来储存字符串  一般用于求字符串前缀的各种问题

附上模板题注释 hdu1251   基本跟上面链接里的模板一样(加了点注释233)  大家也可以用大白书的模板 两个基本一样的

http://acm.hdu.edu.cn/showproblem.php?pid=1251

#include <bits/stdc++.h>
using namespace std;
int trie[1000005][27],tot,root,len;
int sum[1000005];
char a[105];
void insertt()//插入单词
{
     len=strlen(a);//单词的长度
     root=0;//根节点编号为0
    for(int i=0;i<len;i++)
    {
        int id=a[i]-'a';//第二种编号
        if(!trie[root][id])//如果之前没有从root到id的前缀
                    trie[root][id]=++tot;//插入,tot为编号 按字符串的输入顺序编号
                    sum[trie[root][id]]++;//每走过这个结点一次 代表到此结点为止前缀相同的字符串又多了一个
        root=trie[root][id];//顺着字典树往下走
    }
}
int findd()
{
     len=strlen(a);
     root=0;//从根结点开始找
    for(int i=0;i<len;i++)
    {
        int x=a[i]-'a';//
        if(trie[root][x]==0)   return 0;//以root为头结点的x字母不存在,返回0
//        if(!a[i+1])
//            return sum[trie[root][x]];
        root=trie[root][x]; //为查询下个字母做准备,往下走

    }
    return sum[root];
 //   return true;//找到了
}
int main()
{  memset(sum,0,sizeof(sum));
    while(gets(a)){
      if(!a[0])
        break;
        insertt();
    }
    while(cin>>a){
        cout<<findd()<<endl;
    }
    return 0;
}

 

    原文作者:Trie树
    原文地址: https://blog.csdn.net/szudianchuang/article/details/82391618
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞