zoukankan      html  css  js  c++  java
  • 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
    ", query(str));
     42 	}
     43 	return 0;
     44 }
     45 
     46 
     47 
  • 相关阅读:
    通信信号处理的一些基本常识
    欧拉公式
    css3圆角讲解
    css3投影讲解、投影
    css3变形讲解
    浏览器兼容问题
    css3渐变详解
    css中em与px
    복 경 에 갑 니 다 去北京
    我在北京:)
  • 原文地址:https://www.cnblogs.com/rstz/p/13373222.html
Copyright © 2011-2022 走看看