字典树

 

https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html 

这个博客最后还有几道 字典树的模板题

 

这是一道    对于每个提问,给出以该字符串为前缀的单词的数量

#include <iostream>
#include <stdio.h>
using namespace std;

int trie[1000010][26];    //数组形式定义字典树,值存储的是下一个字符的位置
int num[1000010]={0};    //附加值,以某一字符串为前缀的单词的数量
int pos = 1;

void Insert(char word[])    //在字典树中插入某个单词
{
    int i;
    int rt = 0;
    for(i=0;word[i];i++){
        int k = word[i]-'a';
        if(trie[rt][k]==0)    //如果对应字符还没有值
            trie[rt][k] = pos++;
        rt = trie[rt][k];
        num[rt]++;//s[i]的每个字母在树中 被经过 的次数 
    }
}
int Find(char word[])    //返回以某个字符串为前缀的单词的数量
{
    int i;
    int rt = 0;
    for(i=0;word[i];i++){
        int k = word[i]-'a';
        if(trie[rt][k]==0)
            return 0;
        rt = trie[rt][k];
    }
    return num[rt]; //如果能到达这个rt,就输出 经过rt的次数,这样能保证是别的字符串的前缀或者相同 
}

int main()
{
    char word[11];
    while(gets(word)){
        if(word[0]==NULL)    //空行。gets读入的回车符会自动转换为NULL。
            break;
        Insert(word);
    }
    while(gets(word))
        printf("%d\n",Find(word));
    return 0;
}

 

posted @ 2018-08-09 14:05  木流牛马  阅读(81)  评论(0编辑  收藏  举报