字典树模板

字典树

1、定义:又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计

2、优点:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高

3、模板:

const int maxn = 1e5+10;
int ch[maxn][26],tot;
bool bo[maxn];
//初始化 
void Clear()
{
    tot=1;
    memset(ch,0,sizeof(ch));
    memset(bo,false,sizeof(bo));
}
//插入 
void Insert(char *s)
{
    int u=1,i,len=strlen(s),c;
    for(i=0;i<len;i++)
    {
        c=s[i]-'a';
        if(!ch[u][c]) ch[u][c]=++tot;
        u=ch[u][c];
    }
    bo[u]=true;
}
//查找 
bool Search(char *s)
{
    int u=1,len=strlen(s),c;
    for(i=0;i<len;i++)
    {
        c=s[i]-'a';
        if(ch[u][c]) u=ch[u][c];
        else return false;
    }
    return true;
}
View Code
原文地址:https://www.cnblogs.com/2018zxy/p/10311818.html