01字典树贪心查询+建立+删除(个人模版)

时间:2022-05-07
本文章向大家介绍01字典树贪心查询+建立+删除(个人模版),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

01字典树贪心查询+建立+删除:

 1 #define maxn 2
 2 typedef struct tree
 3 {
 4     tree *nex[maxn];
 5     int v;
 6     int val;
 7 }tree;
 8 tree root;
 9 void init()
10 {
11     for(int i=0;i<maxn;i++)
12     {
13         root.nex[i]=NULL;
14     }
15 }
16 void creat(char *str,int va)
17 {
18     int len=strlen(str);
19     tree *p=&root,*q;
20     for(int i=0;i<len;i++)
21     {
22         int id=str[i]-'0';
23         if(p->nex[id]==NULL)
24         {
25             q=(tree *)malloc(sizeof(root));
26             q->v=1;
27             for(int j=0;j<2;j++)
28             {
29                 q->nex[j]=NULL;
30             }
31             p->nex[id]=q;
32         }
33         else
34         {
35             p->nex[id]->v++;
36         }
37         p=p->nex[id];
38         if(i==len-1)
39         {
40             p->val=va;
41         }
42     }
43 }
44 void del(char *str)
45 {
46     int len=strlen(str);
47     tree *p=&root;
48     for(int i=0;i<len;i++)
49     {
50         int id=str[i]-'0';
51         p->nex[id]->v--;
52         tree *tmp=p->nex[id];
53         if(p->nex[id]->v==0)
54         {
55             p->nex[id]=NULL;
56         }
57         p=tmp;
58     }
59     return ;
60 }
61 void find(char *str,int query)
62 {
63     int len=strlen(str);
64     tree *p=&root;
65     for(int i=0;i<len;i++)
66     {
67         int id=str[i]-'0';
68         if(p->nex[1-id]!=0)
69         {
70             p=p->nex[1-id];
71         }
72         else
73         p=p->nex[id];
74         if(p==NULL)
75         return ;
76         if(i==len-1)printf("%dn",p->val^query);
77     }
78 }