trie字典树【模板题】

字典树是一种实现字符串快速检索的多叉树结构。每个节点都拥有很多个指针。

  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 
  5 const int N = 1e6 + 5, M = 5e5 + 5;
  6 
  7 int trie[M][26], tot = 0, cnt[M];//数组模拟树,
  8                                 //cnt[i]是用来记录以i这个节点结束的字符串数量
  9                                 //tot是用来分配节点。
 10 char str[N];
 11 void insert(char* str){
 12 	int p = 0;
 13 	for(int i = 0; str[i]; ++ i) {
 14 		int &s = trie[p][str[i] - 'a'];
 15 		if(!s) s = ++ tot;//如果当前节点为空,就分配一个
 16 		p = s;
 17 	}
 18 	cnt[p] ++;
 19 }
 20 
 21 int query(char* str) {
 22 	int p = 0, res = 0;
 23 	for(int i = 0; str[i]; ++ i) {
 24 		int &s = trie[p][str[i] - 'a'];
 25 		if(!s) break;
 26 		p = s;
 27 		res += cnt[p];//统计前缀字符串
 28 	}
 29 	return res;//返回答案
 30 }
 31 int main() {
 32 	int n, m;
 33 	cin >> n >> m;
 34 	while(n --) {
 35 		scanf("%s", str);
 36 		insert(str);
 37 	}
 38 
 39 	while(m --) {
 40 		scanf("%s", str);
 41 		printf("%d\n", query(str));
 42 	}
 43 	return 0;
 44 }
 45 
 46 
 47 
posted @ 2020-07-24 17:35  ACWink  阅读(192)  评论(0编辑  收藏  举报