版本比较
浅谈字典树
正文
增加 26 行删除 22 行
12234456789101011121314141516171718191920212021222324252625272829283031323133343536353738393840414243444546444748495051525351545553565755585957606162636461656667686970717269737475767778757980818283848185868788895 行未改动# 字典树1.介绍:## 1.介绍:
字典树,顾名思义,就是一颗有字符串构成的树,如图:字典树,顾名思义,就是一颗由字符串构成的树,如图:

有时候,出题人会让我们找某个字符串的前缀,那就可以用它。
2.原理:## 2.原理:
其实很简单,就是取一个字符的值,然后将其标记,最后在查找即可。
3.模板:## 3.模板([P8306 【模板】字典树](https://www.luogu.com.cn/problem/P8306)):
### 1.ge_num函数:取字符的值,因为ASCLL码太大了,所以我们选择自定义值(因为是自定义,所以要偏移,不然记到一起去了)```cppint get_num(char c)//取字符的值,因为ASCLL码太大了,所以我们选择自定义值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 ; // 数字(同上) if(c >= 'a' && c <= 'z') return c - 'a' ; if(c >= 'A' && c <= 'Z') return c - 'A' + 26 ; return c - '0' + 52 ;}```### 2.insert函数:主要是用来标记前缀```cppvoid insert(string s)//标记函数void insert(string s){ int u = 0 ; int len = s.size() ;//字串长度 int len = s.size() ; for(int i = 0 ; i < len ; i ++) { int c = get_num(s[i]) ;//字符对应的数字 int c = get_num(s[i]) ; if(node[u][c] == 0) { tot ++ ; node[u][c] = tot ;//将前缀标记 node[u][c] = tot ; } u = node[u][c] ; cnt[u] ++ ;//前缀个数 cnt[u] ++ ; } vis[u] ++ ;}```### 3.search函数:主要是用来查询前缀个数的```cppint search(string s)//查询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)//没有前缀 if(node[u][c] == 0) { return 0 ;//返回0 return 0 ; } u = node[u][c] ;//前缀 u = node[u][c] ; } return cnt[u] ;//返回前缀个数 return cnt[u] ;}```### 4.主函数:主要进行输入,清空和标记```cppint main()//主函数,主要进行输入,清空和预处理int main(){ int t ; cin >> t ; while(t --) { int n , q ; cin >> n >> q ; for(int i = 0 ; i <= tot ; i ++)//清空 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 ++)//输入+预处理 for(int i = 1 ; i <= n ; i ++) { string s ; cin >> s ; insert(s) ; } for(int i = 1 ; i <= q ; i ++)//输出 for(int i = 1 ; i <= q ; i ++) { string s ; cin >> s ; cout << search(s) << "\n" ;5 行未改动