Trie树 & 01Trie

指针版

#define MAXNUM 26
//定义字典树结构体
typedef struct Trie
{
    bool flag;//从根到此是否为一个单词
    Trie *next[MAXNUM];
}Trie;
//声明一个根
Trie *root;
//初始化该根
void init()
{
    root = (Trie *)malloc(sizeof(Trie));
    root->flag=false;
    for(int i=0;i<MAXNUM;i++)
    root->next[i]=NULL;
}
//对该字典树的插入单词操作
void insert(char *word)
{
    Trie *tem = root;
    while(*word!='')
    {
        if(tem->next[*word-'a']==NULL)
        {
            Trie *cur = (Trie *)malloc(sizeof(Trie));
            for(int i=0;i<MAXNUM;i++)
            cur->next[i]=NULL;
            cur->flag=false;
            tem->next[*word-'a']=cur;
        }
        tem = tem->next[*word-'a'];
        word++;
    }
    tem->flag=true;
}
//查询一个单词的操作
bool search(char *word)
{
    Trie *tem = root;
    for(int i=0;word[i]!='';i++)
    {
        if(tem==NULL||tem->next[word[i]-'a']==NULL)
        return false;
        tem=tem->next[word[i]-'a'];
    }
    return tem->flag;
}
//释放字典树内存操作,由于本题测试数据后程序自动跳出,所以这里没写释放内存函数
void del(Trie *cur)
{
    for(int i=0;i<MAXNUM;i++)
    {
        if(cur->next[i]!=NULL)
        del(cur->next[i]);
    }
    free(cur);
}

 01Trie

 1 struct Trie
 2 {
 3     int root, tot, next[100000*31][2], cnt[100000*31], end[100000*31];
 4 
 5     inline int Newnode()
 6     {
 7         memset(next[tot], -1, sizeof(next[tot]));
 8         cnt[tot] = 0;
 9         end[tot] = 0;
10         return tot ++;
11     }
12 
13     inline void Init()
14     {
15         tot = 0;
16         root = Newnode();
17     }
18 
19     inline void Insert(int x)
20     {
21         int p = root;
22         cnt[p] ++;
23         for(int i = 31; i >= 0; i --)
24         {
25             int idx =  (x >> i) & 1;
26             if(next[p][idx] == -1)
27                 next[p][idx] = Newnode();
28             p = next[p][idx];
29             cnt[p] ++;
30         }
31         end[p] = x;
32     }
33 
34     inline void Del(int x)
35     {
36         int p = root;
37         cnt[p] --;
38         for(int i = 31; i >= 0; i --)
39         {
40             int idx =  (x >> i) & 1;
41             p = next[p][idx];
42             cnt[p] --;
43         }
44     }
45 
46     inline int Search(int x)  //求x的异或最大值,看情况修改
47     {
48         int p = root;
49         for(int i = 31; i >= 0; i --)
50         {
51             int k = (x >> i) & 1;
52             if(next[p][k^1] != -1 && cnt[next[p][k^1]])
53                 p = next[p][k^1];
54             else
55                 p = next[p][k];
56         }
57         return x ^ end[p];
58     }
59 }tr;
原文地址:https://www.cnblogs.com/weeping/p/5931586.html