跳到正文

算法·理论

字典树(trie)-基础应用-总结

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

文章信息

发布
2026年8月24日
收录
2026年8月26日
更新
2026年11月10日
篇幅
约 5 分钟

版本

  1. v1当前

字典树又称trietrie树,或前缀树

定义

如果要判断两个字符串(stringstring)的前缀是否相同,要如何做?

  • Method 1.用forfor循环,一个一个的检索,这个的时间复杂度很高很高(O(nlogn)O(nlogn))

  • Method 2.用哈希进行检索,这样的时间复杂度,还是不够快(O(n)O(n))

  • Method 3.这时候就要用到字典树辣(古希腊掌管MLE的神,我才不会说我在它上面MLE了足足32发)

要搓出它首先要建一个超级源点,然后将两个字符串挂上去,如果他们的前缀相同,就不分开成两个节点,而是变成同一个节点,可以发现,这个时候的空间是输入字符串的总长,而不是单个长度

PS:如果要求后缀相同好像也可以用trie树诶(有待考证?)

好的说完了定义,让我们看看模板吧

模板

C++
#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int N=3e6+25;
int t,n,m,tot;
int node[N][65],cnt[N],vis[N];
int get_num(char c){
	if(c>='a'&&c<='z')return c-'a';
	if(c>='A'&&c<='Z')return c-'A'+26;
	return c-'0'+52; 
}
void insert(string s){
	int u=0,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]++;
	return ;
}
int query(string s){
	int u=0,len=s.size();
	for(int i=0;i<len;i++){
		int c=get_num(s[i]);
		if(node[u][c]==0){
			return 0;
		}
		u=node[u][c];
	}
	return cnt[u];
}
signed main()
{
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>t;
    while(t--)
    {
    	for(int i=0;i<=tot;i++)
    	{
    		cnt[i]=0;
    		for(int j=0;j<65;j++)
    		{
    			node[i][j]=0;
			}
		}
		tot=0;
		cin>>n>>m;
		for(int i=1;i<=n;i++)
		{
			string s;
			cin>>s;
			insert(s);
		}
		for(int i=1;i<=m;i++)
		{
			string s;
			cin>>s;
			cout<<query(s)<<endl;
		}
	}
    return 0;
}
  • second

    这个模板需要题目给前缀,求它是否是一个字符串的前缀

    例题:P10470 前缀统计

    code:

C++
#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
const int N=5e6+25;
int n,m,tot;
int node[N][35],ans[N];
int get_num(char c){
	return c-'a';
}
void insert(string a){
	int u=0;
	for(int i=0;a[i];i++){
		int x=get_num(a[i]);
		if(!node[u][x]){
			tot++;
			node[u][x]=tot;
		}
		u=node[u][x];
	}
	ans[u]++; 
	return ;
}
int query(string a){
	int u=0,sum=0;
	for(int i=0;a[i];i++){
		int x=get_num(a[i]);
		if(!node[u][x])break;
		sum+=ans[node[u][x]];
		u=node[u][x];
	}
	return sum;
}
signed main()
{
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
    	string s;
    	cin>>s;
    	insert(s);
	}
	for(int i=1;i<=m;i++)
    {
    	string t;
    	cin>>t;
    	cout<<query(t)<<endl;
	}
    return 0;
}
原文