-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie_xor.cpp
65 lines (63 loc) · 1.27 KB
/
Trie_xor.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
int curxor = 0 ;
struct Trienode{
struct Trienode* bits[2];
int sum;
};
struct Trienode* newnode(int val){
struct Trienode* temp = new Trienode;
temp->bits[0] = NULL;
temp->bits[1] = NULL;
temp->sum = val;
return temp;
}
void insert(struct Trienode* root,int num){
struct Trienode* pCrawl = root;
for(int i = 33 ; i >=0 ;i--){
if((1LL<<i) & num){
if(pCrawl->bits[1]==NULL){
pCrawl->bits[1] = newnode(0);
}
pCrawl = pCrawl->bits[1];
}
else{
if(pCrawl->bits[0]==NULL){
pCrawl->bits[0] = newnode(0);
}
pCrawl = pCrawl->bits[0];
}
pCrawl->sum++;
}
}
int lol(struct Trienode* root){
if(root){
return root->sum;
}
return 0;
}
int get(struct Trienode* root,int prefix,int k){
struct Trienode* pCrawl = root;
int ans = 0;
for(int i = 33 ; i>=0 ; i--){
if(!pCrawl)break;
int PB = (prefix >> i) & 1LL;
int bit = (k >> i) & 1LL;
if (PB == bit) {
if (PB == 1) {
ans += lol(pCrawl->bits[1]);
}
pCrawl = pCrawl->bits[0];
}
else {
if (PB == 0) {
ans += lol(pCrawl->bits[0]);
}
pCrawl = pCrawl->bits[1];
}
}
return ans;
}
/*
struct Trienode* root = newnode(0);
get(root,curxor,k);
insert(root,curxor);
*/