Trie树

一看名字就知道这是棵树,而且和字符串有关。

就我理解,Trie树是以字符为边,以字符串信息为点的树。可以用于字符串的去重、检索等。

实现的话,将根节点认为是一个特殊的点,从此开始向下保存字符串。设ch[i][j]存储结点i的字符编号为j的孩子的编号,cnt[i]表示以结点i作为结束的字符串数(也可以是其他用途),num为树的结点总数。

这样可以对应每个字符串将其保存在树里,自动去重。查找时,只需对应着边往下找即可。

 1 struct Trie {
 2     int ch[maxn][26],cnt[maxn],num;
 3     Trie() {
 4         memset(ch[0],0,sizeof(ch[0]));
 5         memset(cnt,0,sizeof(cnt));
 6         num=0;
 7     }
 8     int newnode() {
 9         ++num;
10         memset(ch[num],0,sizeof(ch[num]));
11         return num;
12     }
13     void insert(char* s) {
14         int u=0;
15         for(int i=0;s[i];++i) {
16             if(!ch[u][s[i]-'a'])
17                 ch[u][s[i]-'a']=newnode();
18             u=ch[u][s[i]-'a'];
19         }
20         ++cnt[u];
21     }
22     int query(char* s) {
23         int u=0;
24         for(int i=0;s[i];++i) {
25             if(!ch[u][s[i]-'a']) return 0;
26             u=ch[u][s[i]-'a'];
27         }
28         return cnt[u];
29     }
30 };

 

posted @ 2018-09-16 19:42  Mr^Kevin  阅读(167)  评论(0编辑  收藏  举报