Trie字典树

字典树存储字符串,查找方便,迅速;

  • 基本思想就是建立一棵树,每一层都有26个节点(对应26个字母),如果这个字符没有的话就占位,有就通过这个节点向下一层建树
  • 即一个字符串,每个字母对应每一层,对应的层数里面有这个字母就下一层没有就建节点

Trie树例题

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 1e6 + 10;

// trie --> 建立字典树存储字符串 cnt[i] --> 已 i 结尾的字符串总数 idx --> 当前的位置
int trie[N][26], cnt[N], idx;

void insert(char str[]){
    int p = 0;
    for(int i = 0; str[i]; i++){
        int u = str[i] - 'a';
        if(!trie[p][u]) trie[p][u] = ++idx; //没有这个单词,那么建立新节点
        p = trie[p][u];                     // 此时 tire[p][u] 一定建立了
    }
    cnt[p]++ ;                             //已 p 结尾的单词数目加一
}

int search(char str[]){
    int p = 0, ans = 0 ;
    for(int i = 0; str[i]; i++){
        int u = str[i] - 'a';
        if(!trie[p][u]) return ans;       // 没有这个节点,发返回ans
        ans += cnt[trie[p][u]];           //有,则加上cnt[trie[p][u]]这个节点上的所有次数
        p = trie[p][u];
    }
    return ans;
}

int main(){
    int n, m;
    char s[N];
    scanf("%d%d",&n,&m);
    
    for(int i = 1; i <= n; i++){
       scanf("%s",s);
        insert(s);                     //建树
    }
    
    for(int i = 1; i <= m;i++){
        scanf("%s",s);                //目标串
        printf("%d\n",search(s));
    }
    
    return 0;
}
posted @ 2021-02-28 23:23  Carrot_Rui  阅读(51)  评论(0)    收藏  举报