Dictionary tree:
also known as the prefix tree, Trie tree is a tree structure. Typical applications for statistics, sort and save a lot of strings (but not limited to strings). Its advantages are: the use of the common prefix of the string to reduce the query time, minimizing unnecessary string comparison.
Its most basic operation is to insert a string, and query.
Storage structure:
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];
}