题解:P8306 【模板】字典树

· · 题解

#include <bits/stdc++.h>
#define AC return
#define K 0
using namespace std;
int pos, root;
int chs[3000006][65], t[3000006], T, n, q, ans;
string s;
int query(char c)
{
    if(c >= 'a' && c <= 'z')
    {
        AC c - 'a';
    }
    else if(c >= 'A' && c <= 'Z')
    {
        AC c - 'A' + 26;
    }
    else
    {
        AC c - '0' + 52;
    }
}
void dfs(int now, int id, int opt)
{
    if (opt == 1)
    {
        t[now]++;
    }
    if(id == s.size())
    {
        if(opt == 2)
        {
            ans = t[now];
        }
        AC;
    }
    int x = query(s[id]);
    if(chs[now][x] == 0)
    {
        if(opt == 1)
        {
            chs[now][x] = ++pos;
        }
        else
        {
            ans = 0;
            AC;
        }
    }
    dfs(chs[now][x], id + 1, opt);
}
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> T;
    while (T--)
    {
        pos = 1, root = 1;
        cin >> n >> q;
        while (n--)
        {
            cin >> s;
            dfs(root, 0, 1);
        }
        while (q--)
        {
            cin >> s;
            dfs(root, 0, 2);
            cout << ans << '\n';
        }
        for (int i = 1; i <= pos; i++)
        {
            t[i] = 0;
            for (int j = 0; j < 62; j++)
            {
                chs[i][j] = 0;
            }
        }
    }
    AC K;

}