跳到正文

个人记录

P8306 【模板】字典树

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

文章信息

发布
2024年4月13日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 5 分钟

版本

  1. v1当前

刚学字典树,切个板子


字典树是一棵树,用于高效处理不同字符串的字串的存在和数量

相应的字符存在相应的边上


为什么不能存在点上呢

1.会导致误判 2.不方便


具体如何实现


创建

1.初始点p为1,然后寻找子串中值为第i(初始为0)个字符的边e;

2.若有,p转移到e连接的节点上,重复1直到寻完整个字符串;

3.若没有,新建一个e连到新节点上,p转到新节点;

4.爬完之后,给最后爬到的点p打个end标记


查找

同理

Code:
C++
#include <bits/stdc++.h>
#define str string
#define MAXN 3000005
using namespace std;
int hash_(char ch){
	if(ch>='A'&&ch<='Z') return ch-'A';
	if(ch>='0'&&ch<='9') return ch-'0'+26;
	return ch-'a'+36;
}
struct Trie{
	int cnt,edge[MAXN][27*2+10];//edge是相应的边,cnt是计数器,加节点用的 
	int end[MAXN];
	
	//初始化 
	void fir(){
		for(int i=1;i<=cnt;++i){
			for(int j=0;j<27*2+10;++j) edge[i][j]=0;
			end[i]=0;
		}
		cnt=1;
	}
	//加字符串 
	void add(str s){
		int len=s.size();//len为字符串长度
		int p=1,i;//p为当前节点,i就是爬一遍s的指针 
		while(i<len){
			int h=hash_(s[i]);//字符的hash值 
			if(!edge[p][h]) edge[p][h]=++cnt;//没有对应的边就加边连到新的节点 
			p=edge[p][h];//p转换到下一个点 
			++i;
		}
		end[p]=1;//打标记 
	}
	//查找是否存在 
	bool in(str s){
		int len=s.size();
		int p=1,i;
		while(i<len){
			int h=hash_(s[i]);
			if(!edge[p][h]) return false;
			p=edge[p][h];//基本同上,不过没有加边直接返回false,毕竟不可能有相应字串了 
			++i;
		}
		if(end[p]) return true;//如果不是结尾的话还是不算的,原因很容易想 
		return false;
	}
};

回到题目上来

这样一看就很裸了

是前缀的话就不用判end了,但是个数该怎么算呢

可以end来统计到相应节点的有几个串

查找的时候end是几就有几个串有相应前缀

AC Code:
C++
#include <bits/stdc++.h>
#define str string
#define MAXN 3000005
using namespace std;
int hash_(char ch){
	if(ch>='A'&&ch<='Z') return ch-'A';
	if(ch>='0'&&ch<='9') return ch-'0'+26;
	return ch-'a'+36;
}
struct Trie{
	int cnt,edge[MAXN][27*2+10];
	int end[MAXN];
	
	void fir(){
		for(int i=1;i<=cnt;++i){
			for(int j=0;j<27*2+10;++j) edge[i][j]=0;
			end[i]=0;
		}
		cnt=1;
	}
	void add(str s){
		int len=s.size();
		int p=1,i;
		while(i<len){
			end[p]++;
			int h=hash_(s[i]);
			if(!edge[p][h]) edge[p][h]=++cnt;
			p=edge[p][h];
			++i;
		}
	}
	int in(str s){
		int len=s.size(),num=0;
		int p=1,i;
		while(i<len){
			int h=hash_(s[i]);
			if(!edge[p][h]) return 0;
			p=edge[p][h];
			++i;
		}
		return end[p];
	}
};


int t,n,q;
Trie trie;
int main(){
	cin>>t;
	for(int i=0;i<t;++i){
		
		trie.fir();
		cin>>n>>q;
		for(int j=0;j<n;++j){
			str s;
			cin>>s;
			trie.add(s);
		}
		for(int j=0;j<q;++j){
			str s;
			cin>>s;
			cout<<trie.in(s)<<'\n';
		}
	}
	return 0;
}

哎呀,题面忘贴了

隙间传送门

(其实应该带点图的,不过我太懒了orz)

原文