16求条

P8306 【模板】字典树

_XSOI_ @ 2024-07-20 17:25:08

#include <iostream>
using namespace std;
const int N = 3e6 + 11;
char s[N];
int ch[N][26],cnt[N],idx;
// ch[i][j] 由节点i沿着char(j)这条边指向的节点的映射值
int n,q,T;
void insert(char *s) {
    int p = 0;
    for (int i = 0; s[i]; i ++) {
        int j = s[i] - 'a'; // 映射
        if (!ch[p][j]) {
            ch[p][j] == ++ idx;
        }
        p = ch[p][j];
    }
    cnt[p] ++;
}
int query(char *s) {
    int p = 0;
    for (int i = 0; s[i]; i ++) {
        int j = s[i] - 'a'; // 映射
        if (!ch[p][j]) {
            return 0; // 它不存在
        }
        p = ch[p][j];
    }
    return cnt[p];
}
signed main() {
    cin >> T;
    while (T --) {
        for (int i = 0; i <= idx; i ++) {
            for (int j = 0; j <= 26; j ++) {
                ch[i][j] = 0;
            }
        }
        for (int i = 0; i <= idx; i ++) {
            cnt[i] = 0;
        }
        idx = 0;
        // 初始化
        cin >> n >> q;
        while (n --) {
            cin >> s;
            insert(s);
        }
        while (q --) {
            cin >> s;
            printf("%d\n",query(s));
        }
    }
    return 0;
}

by _XSOI_ @ 2024-07-20 17:25:29

@Genius_star


|