跳到正文

算法·理论

浅谈字典树

yy2014约 3 分钟
原文

这是 2025年10月19日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年10月19日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

字典树

1.介绍:

字典树,顾名思义,就是一颗有字符串构成的树,如图:

有时候,出题人会让我们找某个字符串的前缀,那就可以用它。

2.原理:

其实很简单,就是取一个字符的值,然后将其标记,最后在查找即可。

3.模板:

C++
int get_num(char c)//取字符的值,因为ASCLL码太大了,所以我们选择自定义值
{
	if(c >= 'a' && c <= 'z') return c - 'a' ; // 小写字母
	if(c >= 'A' && c <= 'Z') return c - 'A' + 26 ; // 大写字母(因为是自定义,所以要偏移,不然记到一起去了)
	return c - '0' + 52 ; // 数字(同上)
}
C++
void insert(string s)//标记函数
{
	int u = 0 ;
	int len = s.size() ;//字串长度
	for(int i = 0 ; i < len ; i ++)
	{
		int c = get_num(s[i]) ;//字符对应的数字
		if(node[u][c] == 0)
		{
			tot ++ ;
			node[u][c] = tot ;//将前缀标记
		}
		u = node[u][c] ;
		cnt[u] ++ ;//前缀个数
	}
	vis[u] ++ ;
}
C++
int search(string s)//查询
{
	int u = 0 ;
	int len = s.size() ;
	for(int i = 0 ; i < len ; i ++)
	{
		int c = get_num(s[i]) ;
		if(node[u][c] == 0)//没有前缀
		{
			return 0 ;//返回0
		}
		u = node[u][c] ;//前缀
	}
	return cnt[u] ;//返回前缀个数
}
C++
int main()//主函数,主要进行输入,清空和预处理
{
	int t ;
	cin >> t ;
	while(t --)
	{
		int n , q ;
		cin >> n >> q ;
		for(int i = 0 ; i <= tot ; i ++)//清空
		{
			cnt[i] = 0 ;
			for(int j = 0 ; j < 65 ; j ++) node[i][j] = 0 ;
		}
		tot = 0 ;
		for(int i = 1 ; i <= n ; i ++)//输入+预处理
		{
			string s ;
			cin >> s ;
			insert(s) ;
		}
		for(int i = 1 ; i <= q ; i ++)//输出
		{
			string s ;
			cin >> s ;
			cout << search(s) << "\n" ;
		}
	}
	return 0 ;
}