跳到正文

题解

题解:P8306 【模板】字典树

Lyzc0dr约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月23日
篇幅
约 5 分钟
获赞
1
题目
P8306

版本

  1. v1当前

前言

考古半年前学过的字典树,居然发现模板都没有人写题解(太恐怖了,毕竟想要找到蒟蒻能写题解的题目还是不多的,特别还是模板题,可算是稀有中的稀有),于是发了一篇。

字典树

基本概念

字典树,就是一种可以在一些字符串中快速判断字符串前缀的树形数据结构,本处给出一张图便于理解(敬请原谅画图)。 观察图片可得:

  1. 每个节点代表一个字符。
  2. 根节点是没有字符的。
  3. 可以发现其中的每个点从上至下的字符连起来从左至右可以拼成 ash,bet,bee,cat,cap 四个单词,且可以发现,其中前缀相同的单词会将前缀“合并”,并只在公共的前缀后添加自己独有的字符,简单来说,就是每个节点所包含在内的其他子节点的字符两两不同,这样在题目中便可以运用这个性质进行前缀查询与计数。

构造

其实在理解了原理之后,字典树的插入、查询操作就呼之欲出了。

1.字符串的插入

每次进行向后的搜寻,同时遍历字符串,如果本字符在各个点中没有出现过,就添加这个字符所对应的点,否则就顺着已经建好的点往下走,并在该节点后增加标记。

C++
void ins(const string &s) {
        int p=0;
        for(char c:s) {
            int ch=getIdx(c);//此函数表示获取此字符的编号
            if(!trie[p][ch]) trie[p][ch]=++cnt_node;
            p=trie[p][ch];
            cnt[p]++;
        }
    }

2.查询

将进行查询的字符串遍历,最后得到上面插入时统计的标记数量。

C++
int find(const string &s) {
        int p=0;
        for(char c:s) {
            int ch=getIdx(c);//同上
            if(!trie[p][ch]) return 0;
            p=trie[p][ch];
        }
        return cnt[p];
    }

以上就是字典树的基本操作,其他操作的变种均源自上方的基本操作。

本题

本题中需要注意多测需每次清空。

C++
void clear() {
        for(int i=0;i<=cnt_node;i++) {
            memset(trie[i],0,sizeof(trie[i]));
            cnt[i]=0;
        }
        cnt_node=0;
    }

本题的思路不作解释,均为上文提到概念的基本运用,下面给出完整代码。

C++
#include <bits/stdc++.h>
#define endl "\n"
#define ll long long
#define pii pair<int,int>
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
using namespace std;
const int N=3e6+10;
namespace Trie {
    int trie[N][62], cnt[N], cnt_node;
    int getIdx(char c) {//上文提到的字符编号查询
        if(islower(c)) return c-'a';
        if(isupper(c)) return c-'A'+26;
        return c-'0'+52;
    }
    void ins(const string &s) {//插入
        int p=0;
        for(char c:s) {
            int ch=getIdx(c);
            if(!trie[p][ch]) trie[p][ch]=++cnt_node;
            p=trie[p][ch];
            cnt[p]++;
        }
    }
    int find(const string &s) {//查询
        int p=0;
        for(char c:s) {
            int ch=getIdx(c);
            if(!trie[p][ch]) return 0;
            p=trie[p][ch];
        }
        return cnt[p];
    }
    void clear() {//清空
        for(int i=0;i<=cnt_node;i++) {
            memset(trie[i],0,sizeof(trie[i]));
            cnt[i]=0;
        }
        cnt_node=0;
    }
}
int main() {
    IOS
    int T,n,q;
    cin>>T;
    while(T--) {
        cin>>n>>q;
        string s;
        for(int i=1;i<=n;i++) {
            cin>>s;
            Trie::ins(s);
        }
        while(q--) {
            cin>>s;
            cout<<Trie::find(s)<<endl;
        }
        Trie::clear();
    }
    return 0;
}
原文