题解:P8306 【模板】字典树

· · 题解

题目传送门

字典树的定义

具体而言,就是一棵边权是字母的树,且以根节点为起点的某些树上的路径代表着一些被存储进来的字符串。 多用于求解字符串是否出现在别的字符串前缀的问题。 # 实现方法 ## 如何将字符串加入树中 想要将一个字符串加入树中,应先一位一位枚举,如果当前位与下一位无连边,就新建边,如果有就继续遍历下去,代码如下。 ```cpp void insert(string s) { int l=s.size(); int u=0; for(int i=0;i<l;i++) { int x=zh(s[i]);//离散化思想 if(!c[u][x]) { ++tot; memset(c[tot],0,sizeof(c[tot])); cnt[tot]=0;//重置 c[u][x]=tot;//加入 } u=c[u][x];//继续遍历 cnt[u]++;//记录 } } ``` ## 如何查找一个字符串在树中是否出现 一位一位枚举,往下走下去,如果某一位在树中没有对应节点,就说明没有。如果每一位都有,那就说明它在树中出现过,代码如下。 ```cpp int find(string s) { int l=s.size(); int u=0; for(int i=0;i<l;i++) { int x=zh(s[i]);//离散化思想 if(!c[u][x]) return 0;//没有,退出 u=c[u][x];//继续遍历 if(!u)return 0;//没有,退出 } return cnt[u];//返回数量 } ``` ### 图解 ![](https://cdn.luogu.com.cn/upload/image_hosting/l4htcimp.png) 如图,在查找字符串 $aa$ 时,先从根节点 $0$ 开始,点 $1$ 和点 $2$ 之间的边权为 $a$,遂走至点 $2$,点 $2$ 与点 $4$ 间有边权为 $a$,遂走至点 $4$ ,证明该字符串存在。 ## 防止内存和时间爆炸 将字符按离散化思想转换为数字存储,代码如下。 ```cpp int zh(char x) { if(x>='a'&&x<='z')return x-'a'+1; if(x>='A'&&x<='Z')return x-'A'+1+26; if(x>='0'&&x<='9')return x-'0'+1+52; } ``` 在多测时处理每一位时应先将其重置在继续。 ```cpp memset(c[tot],0,sizeof(c[tot])); cnt[tot]=0; ``` # 代码如下 ```cpp #include<bits/stdc++.h> using namespace std; int c[3000005][65],cnt[3000005]; int tot=0; int zh(char x) { if(x>='a'&&x<='z')return x-'a'+1; if(x>='A'&&x<='Z')return x-'A'+1+26; if(x>='0'&&x<='9')return x-'0'+1+52; } void insert(string s)//加入 { int l=s.size(); int u=0; for(int i=0;i<l;i++) { int x=zh(s[i]); if(!c[u][x]) { ++tot; memset(c[tot],0,sizeof(c[tot])); cnt[tot]=0; c[u][x]=tot; } u=c[u][x]; cnt[u]++; } } int find(string s)//查找 { int l=s.size(); int u=0; for(int i=0;i<l;i++) { int x=zh(s[i]); if(!c[u][x]) return 0; u=c[u][x]; if(!u)return 0; } return cnt[u]; } int main() { int t; cin>>t; while(t--) { tot=0;//根节点重置 memset(c[0],0,sizeof(c[0]));//重置 int n,m; cin>>n>>m; string s; for(int i=1;i<=n;i++) { cin>>s; insert(s); } for(int i=1;i<=m;i++) { cin>>s; cout<<find(s)<<endl; } } return 0; } ```