trie T了
查看原帖
trie T了
534597
__PRO__楼主2024/1/2 19:36
#include <iostream>
#include <unordered_map>
using namespace std;

/* ~~~ 模板 ~~~ */
template <int N>
struct trie {
    int cnt;
    struct node {
        unordered_map<char, int> son;
        int end;
    }* t;
    trie()
    {
        t = new node[N];
        clear();
    }
    ~trie()
    {
        delete[] t;
    }
    void clear()
    {
        cnt = 0;
        for (int i = 0; i < N; ++i) {
            t[i].son.clear();
            t[i].end = t[i].end = 0;
        }
    }
    void insert(const char* s)
    {
        int now = 0;
        for (int i = 0; s[i]; ++i) {
            char ch = s[i];
            if (!t[now].son[ch])
                t[now].son[ch] = ++cnt;
            now = t[now].son[ch];
            ++t[now].end;
        }
    }
    int find(const char* s)
    {
        int now = 0;
        for (int i = 0; s[i]; ++i) {
            char ch = s[i];
            if (!t[now].son[ch])
                return 0;
            now = t[now].son[ch];
        }
        return t[now].end;
    }
    void swap(trie<N>& tr)
    {
        swap(t, tr.r);
    }
};
/* ~~~ 模板 ~~~ */

trie<3000010> t;
char s[3000010];
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int T;
    cin >> T;
    while (T--) {
        t.clear();
        int n, q;
        cin >> n >> q;
        while (n--) {
            cin >> s;
            t.insert(s);
        }
        while (q--) {
            cin >> s;
            cout << t.find(s) << '\n';
        }
    }
    return 0;
}
2024/1/2 19:36
加载中...