Trie 模版

 1 //时间复杂度 O(NC) N为节点个数,C是字符集大小
 2 
 3 int trie[N][26], cnt[N], tot=1;
 4 // 0号点既是根节点,又是空节点
 5 // trie[][]存储树中每个节点的子节点
 6 // cnt[]存储以每个节点结尾的单词数量
 7 
 8 // 插入一个字符串
 9 inline void insert(char *str)
10 {
11     int p = 1;
12     for (int i = 0; str[i]; i ++ )
13     {
14         int ch = str[i] - 'a';
15         if (!trie[p][ch]) trie[p][ch] = ++ tot;
16         p = trie[p][ch];
17     }
18     cnt[p] ++ ;
19 }
20 
21 // 查询字符串出现的次数
22 inline int query(char *str)
23 {
24     int p = 1;
25     for (int i = 0; str[i]; i ++ )
26     {
27         int ch = str[i] - 'a';
28         if (!trie[p][ch]) return 0;
29         p = trie[p][ch];
30     }
31     return cnt[p];
32 }

猜你喜欢

转载自www.cnblogs.com/hhyx/p/12528880.html