首页 > 代码库 > 字典树

字典树

 1 const int maxn = 1e5 + 7;
 2 const int SIZE = 10;// 字符数量,如小写字母改为26,记得修改getid
 3 
 4 struct Dictionary_tree{
 5     int cnt;
 6     int next[maxn][SIZE];
 7     int val[maxn];
 8 
 9     void init(){
10         cnt = 0;
11         memset(next[cnt],-1,sizeof(next[cnt]));
12         val[0] = 0;
13     }
14 
15     void add(){
16         cnt++;
17         memset(next[cnt],-1,sizeof(next[cnt]));
18         val[cnt] = 0;
19     }
20     int getid(char c){
21         return c - 0;
22     }
23     int build(char *s,int v){
24         int now = 0;
25         for(int i=0;s[i];i++){
26             int id = getid(s[i]);
27             if(next[now][id] == -1){
28                 add();
29                 next[now][id] = cnt;
30             }
31             now = next[now][id];
32             if(val[now] == 1) return 1;
33         }
34         val[now] = v;
35         return 0;
36     }
37 
38     int query(char *s){
39         int now = 0;
40         for(int i=0;s[i];i++){
41             int id = getid(s[i]);
42             if(next[now][id] == -1) return -1;
43             now = next[now][id];
44         }
45         return val[now];
46     }
47 }tre;

 

字典树