正文
增加 26 行删除 22 行
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384855 行未改动# 字典树1.介绍:字典树,顾名思义,就是一颗有字符串构成的树,如图:有时候,出题人会让我们找某个字符串的前缀,那就可以用它。2.原理:其实很简单,就是取一个字符的值,然后将其标记,最后在查找即可。3.模板:```cppint 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 ; // 数字(同上)}``````cppvoid 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] ++ ;}``````cppint 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] ;//返回前缀个数}``````cppint 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" ;5 行未改动12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788895 行未改动# 字典树## 1.介绍:字典树,顾名思义,就是一颗由字符串构成的树,如图:有时候,出题人会让我们找某个字符串的前缀,那就可以用它。## 2.原理:其实很简单,就是取一个字符的值,然后将其标记,最后在查找即可。## 3.模板([P8306 【模板】字典树](https://www.luogu.com.cn/problem/P8306)):### 1.ge_num函数:取字符的值,因为ASCLL码太大了,所以我们选择自定义值(因为是自定义,所以要偏移,不然记到一起去了)```cppint 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 ;}```### 2.insert函数:主要是用来标记前缀```cppvoid 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] ++ ;}```### 3.search函数:主要是用来查询前缀个数的```cppint 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 ;}u = node[u][c] ;}return cnt[u] ;}```### 4.主函数:主要进行输入,清空和标记```cppint 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" ;5 行未改动