算法入门之Trie树

字典树入门:

Trie树(前缀树)又称字典树,通过树形结构来构造各个字符串,通过数字式,形成一个体系,

root根节点,连接各个子节点,并附加字符信息,从而,达到快速查询手段,来了解想要的信息。

以此为模:http://acm.hdu.edu.cn/showproblem.php?pid=1251

Trie算法技巧:

1.构造树形,初始化。信息包含:每段字符统计个数ncount,树结构的next[]数组。

const int maxn=26;
struct trie
{
    int ncount;
    trie *next[maxn];
    trie()
    {
        ncount=0;
        memset(next,NULL,sizeof(next));
    }
}*root;
char keyword[maxn];
char str[maxn];

2.插入操作,赋值。当前next指向为空,新建空间;否则指向下个指针,并记录ncount。

void insert(trie *p,char *s)
{
    int i=0;
    while(s[i])
    {
        int j=s[i]-'a';
        if(p->next[j]==NULL)
            p->next[j]=new trie();
        p=p->next[j];
        i++;
        p->ncount++;
    }
}

3.查询。不断通过next[],找不到,返回0,否则结束返回指向ncount;

int query(trie *p,char *s)
{
    int i=0;
    int cnt=0;
    while(s[i])
    {
        int j=s[i++]-'a';
        if(p->next[j])
        {
            p=p->next[j];
            cnt=p->ncount;
        }
        else
            return 0;
    }
    return cnt;
}

4.加上main函数。

int main()
{
    int i,j;
    root=new trie();
    while(gets(keyword)&&keyword[0])
    {
        insert(root,keyword);
    }
    while(gets(str))
    {
        printf("%d\n",query(root,str));
    }
    delete root;
    return 0;
}

5.总结。Trie树,刚入门学习。很多不懂变换。

写的第一章算法,还不太会该blog用途。


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