Loading

字典树模板

字典树

预定义

 1 const int N = 1e6+10;
 2 int tot = 1;
 3 struct node
 4 {
 5     int son[26];
 6     int cnt;   // 特殊标记
 7     bool have;
 8     node()
 9     {
10         memset(son,0,sizeof son);
11         cnt = 0;
12         have = false;
13     }
14 }trie[N];

插入

 1 void Insert(char *s)
 2 {
 3     int len = strlen(s);
 4     int u = 0,v;
 5     for(int i = 0;i < len;i++)
 6     {
 7         v = s[i]-'a';
 8         if(!trie[u].son[v])
 9             trie[u].son[v] = tot++;
10         u = trie[u].son[v];
11     }
12     trie[u].have = true;
13 }

 

查找

 1 int Find(char *s)
 2 {
 3     int len = strlen(s);
 4     int u = 0,v;
 5     for(int i = 0;i < len;i++)
 6     {
 7         v = s[i]-'a';
 8         if(!trie[u].son[v])
 9             return 0;
10         u = trie[u].son[v];
11     }
12     if(!trie[u].have)   // 没有这个单词
13         return 0;
14     if(!trie[u].cnt)   // 没被查询过
15     {
16         trie[u].cnt++;
17         return 1;
18     }
19     return 0;
20 }

注意

涉及到多组输入的时候可以这样处理

 1 struct node
 2 {
 3     int son[26];
 4     int cnt;   // 特殊标记
 5     bool have;
 6     void clear
 7     {
 8         memset(son,0,sizeof son);
 9         cnt = 0;
10         have = false;
11     }
12 }trie[N];
13 
14 int main()
15 {
16     trie[0].clear();
17 }

01字典树

预定义

 1 const int N = 1e6+100;
 2 int tot = 1;
 3 struct node
 4 {
 5     int son[2];
 6     int size;
 7     node()
 8     {
 9         memset(son,0,sizeof son);
10         size = 0;
11     }
12 }trie[32*N];

插入

 1 void Insert(int x)
 2 {
 3     int root = 1;
 4     trie[root].size++;
 5     for(int k = 30;k >= 0;k--)
 6     {
 7         int tmp = 0;
 8         if(x & (1<<k))
 9             tmp = 1;
10         if(!trie[root].son[tmp])
11             trie[root].son[tmp] = ++tot;
12         root = trie[root].son[tmp];
13         trie[root].size++;
14     }
15 }

删除

 1 void Delete(int x)
 2 {
 3     int root = 1;
 4     trie[root].size--;
 5     for(int k = 30;k >= 0;k--)
 6     {
 7         int tmp = 0;
 8         if(x & (1<<k))
 9             tmp = 1;
10         root = trie[root].son[tmp];
11         trie[root].size--;
12     }
13 }

查询

 1 int Query(int x)
 2 {
 3     int root = 1;
 4     for(int k = 30;k >= 0;k--)
 5     {
 6         int tmp = 0;
 7         if(x & (1<<k))
 8             tmp = 1;
 9         if(tmp)
10         {
11             if(trie[root].son[0] && trie[trie[root].son[0]].size)
12                 root = trie[root].son[0];
13             else 
14                 root = trie[root].son[1],x ^= (1<<k);
15         }
16         else 
17         {
18             if(trie[root].son[1] && trie[trie[root].son[1]].size)
19                 root = trie[root].son[1],x ^= (1<<k);
20             else 
21                 root = trie[root].son[0];
22         }
23     }
24     return x;
25 }

 

习题

CF 706 D. Vasiliy’s Multiset

Chip Factory (ACM Changchun 2015)

HDU 4825 Xor Sum

求完美序列度(待解决)

 

posted @ 2021-01-20 18:16  Yiduuannng  阅读(85)  评论(0编辑  收藏  举报