1. 程式人生 > 實用技巧 >trie字典樹【模板題】

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