字典树:
又称前缀树,Trie树,是一种树形结构。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串)。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较。
它的最基本的操作是插入一个字符串,和查询。
存储结构:
const int maxnode = maxn*maxlen; //字符串个数*字符串的长度
int trie[maxnode][size],tot=0; //size是字符集的大小,tot保存节点个数
bool end[maxnode] // 结尾标记
Insert
int idx(char c)
{
return c - 'a';
}
void insert(char* str)
{
int len = strlen(str),p=0; //根节点为0
for(int i=0;i<len;i++)
{
int id = idx(str[i]);
if(!trie[p][id]) //如果这个节点不存在,新建一个
trie[p][id]= ++tot;
p = trie[p][id];
}
end[p]=true;
}
Find
bool find(char* str)
{
int len = strlen(str),p=0;
for(int i=0;i<len;i++)
{
p = trie[p][idx(str[i])];
if(!p) return false;
}
return end[p];
}