字典树

#include <iostream>
#include <cstring>
#include<string>
using namespace std;
const int N = 1e6 + 10;
int tree[N][26], p[N], e[N];
int idx; 
//插⼊字符串:
void insert(string& s){
    int cur = 0; // 从根结点开始 
    p[cur]++; // 这个格⼦经过⼀次 
    for(auto ch : s){
        int path = ch - 'a';
        // 如果没有路 
        if(tree[cur][path] == 0) tree[cur][path] = ++idx;
        cur = tree[cur][path];
        p[cur]++;
    }
    e[cur]++;
}

//查询字符串出现的次数:
int find(string& s){
    int cur = 0;
    for(auto ch : s){
        int path = ch - 'a';
        if(tree[cur][path] == 0) return 0;
        cur = tree[cur][path];
    }
    return e[cur];
}
//查询有多少个单词以字符s 为前缀:
int find_pre(string& s){
    int cur = 0;
    for(auto ch : s){
        int path = ch - 'a';
        if(tree[cur][path] == 0) return 0;
        cur = tree[cur][path];
    }
    return p[cur];
}
int main(){
    cin.tie(nullptr)->sync_with_stdio(false);
    int T;
    cin>>T;
    while(T--){
        // 清空之前的数据 
        // memset(tr, 0, sizeof tr);
        // memset(p, 0, sizeof p);
        for(int i = 0; i <= idx; i++){
            for(int j = 0; j < 62; j++){
                tree[i][j] = 0;
            }
        }
        for(int i=0;i<=idx;i++)
            p[i]=0;
        idx=0;
        int n,q;
        cin>>n>>q;
        while(n--){
            string s;cin>>s;
            insert(s);
        }
        while(q--){
            string s;cin>>s;
            cout<<find_pre(s)<<endl;
        }
    }
    return 0;
}
posted @ 2025-08-20 19:26  xdhking  阅读(10)  评论(0)    收藏  举报