字典树 Trie
字典树是一种处理字符串匹配的数据结构,适用于字符串以及字符串前后缀的匹配问题。
字典树的优势:
- 擅长处理前缀问题
- 空间利用效率随着字符串数量的增长提升
具体如何实现?
字典树,顾名思义就是一棵树,每一个节点(根节点除外)都代表一个字母。

如图所示,也可以理解成每条边上有一个字母,把边上的字母转移到儿子节点就一样的。
那么前文提到的"适用于字符串以及字符串前后缀的匹配问题"就显而易见了,从根节点出发,每经过一个节点就在末尾加上该节点上的字母,就可以形成很多字符串的前缀,比如aa,ba,caa,cb等。
有时需要标记插入进 trie 的是哪些字符串,每次插入完成时在这个字符串所代表的节点处打上标记即可。
比模板题还模板的模板题
P2580 于是他错误的点名开始了
对所有名字建 trie,再在 trie 中查询字符串是否存在、是否已经点过名,第一次点名时标记为点过名。
cpp
#include<bits/stdc++.h>
using namespace std;
int trie[1000005][30],tot=0;
bool exc[1000005];
map<string,bool> p;
void tree(string s){
int x=0,l=s.size();
s=" "+s;
for(int i=1;i<=l;i++){
int c=s[i]-'a';
if(!trie[x][c]){
trie[x][c]=++tot;
}
x=trie[x][c];
}
exc[x]=1;
}
bool search(string s){
int x=0,l=s.size();
s=" "+s;
for(int i=1;i<=l;i++){
int c=s[i]-'a';
if(!trie[x][c]){
return 0;
}
x=trie[x][c];
}
return exc[x];
}
int main(){
int n,m;
cin>>n;
while(n--){
string s;
cin>>s;
tree(s);
}
cin>>m;
while(m--){
string s;
cin>>s;
if(!search(s)){
cout<<"WRONG"<<endl;
}else if(p[s]){
cout<<"REPEAT"<<endl;
}else{
cout<<"OK"<<endl;
p[s]=1;
}
}
return 0;
}
字典树模板题
P8306 【模板】字典树
题意:询问 t 是多少串的前缀。
- 设 t 的 trie 树上的终止节点为 p,那么以 t 为前缀的字符串的终止节点一定在 p 的子树内。
- 维护 cnt[i] 表示节点 i 被经过的次数。
- 建树时维护 cnt 数组,询问时返回 cnt[p] 就是以 t 为前缀的字符串的数量。
cpp
#include<bits/stdc++.h>
using namespace std;
int trie[3000005][65],tot=0;
int cnt[3000005];
int cont(char x){
if(x<='9'&&x>='0'){
return x-'0';
}
if(x<='z'&&x>='a'){
return x-'a'+10;
}
return x-'A'+36;
}
void tree(string s){
int x=0,l=s.size();
s=" "+s;
for(int i=1;i<=l;i++){
int c=cont(s[i]);
if(!trie[x][c]){
trie[x][c]=++tot;
}
x=trie[x][c];
cnt[x]++;
}
}
int search(string s){
int x=0,l=s.size();
s=" "+s;
for(int i=1;i<=l;i++){
int c=cont(s[i]);
if(!trie[x][c]){
return 0;
}
x=trie[x][c];
}
return cnt[x];
}
int main(){
int t;
cin>>t;
while(t--){
int n,q;
cin>>n>>q;
for(int i=1;i<=n;i++){
string s;
cin>>s;
tree(s);
}
for(int i=1;i<=q;i++){
string s;
cin>>s;
cout<<search(s)<<endl;
}
for(int i=0;i<=tot;i++){//要用循环清空,不然会超时
for(int j=0;j<=64;j++){
trie[i][j]=0;
}
cnt[i]=0;
}
tot=0;
}
return 0;
}
P2922
题意:给定 m 个字符串,查询 n 次,每次询问字符串 s 是多少串的前缀以及多少串是 s 的前缀。
- s 是多少串的前缀。直接维护 cnt 数组同上。
- 多少串是 s 的前缀,询问时走到 s 的终止节点的过程中经过了多少个被染色的节点。
- 第一部分和第二部分可能会有重复,那么只统计其中一种情况即可。
cpp
#include<bits/stdc++.h>
using namespace std;
int trie[500005][2],tot=0;
int cnt[500005],uns[500005];
void tree(string s){
int x=0,l=s.size();
s=" "+s;
for(int i=1;i<=l;i++){
int c=s[i]-'0';
if(!trie[x][c]){
trie[x][c]=++tot;
}
x=trie[x][c];
cnt[x]++;
}
uns[x]++;
}
int search(string s){
int x=0,l=s.size(),ans=0;
s=" "+s;
for(int i=1;i<=l;i++){
int c=s[i]-'0';
if(!trie[x][c]){
return ans;
}
x=trie[x][c];
ans+=uns[x];
}
return ans+cnt[x]-uns[x];
}
int main(){
int m,n;
cin>>m>>n;
for(int i=1;i<=m;i++){
int b;
cin>>b;
string s="";
while(b--){
char x;
cin>>x;
s+=x;
}
tree(s);
}
for(int i=1;i<=n;i++){
int b;
cin>>b;
string s="";
while(b--){
char x;
cin>>x;
s+=x;
}
cout<<search(s)<<endl;
}
return 0;
}