首页 > 代码库 > Tire

Tire

字符串模板第一发,Tire(前缀树)。

 1 const int maxnode = 4005*100;
 2 const int sigma_size = 30;
 3 
 4 class tire{
 5 public:
 6     int ch[maxnode][sigma_size];
 7     int val[maxnode];
 8     int sz;
 9     tire(){
10         sz = 1;
11         mset(ch[0]);
12     }
13     int idx(char c) { return c - a; }
14 
15     void insert(char *s, int v){
16         int u = 0, n = strlen(s);
17         for(int i = 0; i < n; i++){
18             int c = idx(s[i]);
19             if(!ch[u][c]){
20                 mset(ch[sz]);
21                 val[sz] = 0;
22                 ch[u][c] = sz++;
23             }
24             u = ch[u][c];
25         }
26         val[u] = v;
27     }
28 
29     int find(char *s){
30         int u = 0;
31         for(int i = 0; s[i]; i++){
32             int c = idx(s[i]);
33             if(!ch[u][c]) return 0;
34             u = ch[u][c];
35         }
36         return val[u];
37     }
38 };
View Code