-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path1803.Count-Pairs-With-XOR-in-a-Range.cpp
88 lines (85 loc) · 2.21 KB
/
1803.Count-Pairs-With-XOR-in-a-Range.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Solution {
class TrieNode
{
public:
TrieNode* next[2];
int cnt;
TrieNode()
{
for (int i=0; i<2; i++)
next[i] = NULL;
cnt=0;
}
};
public:
int countPairs(vector<int>& nums, int low, int high)
{
return countSmallerPairs(nums, high+1) - countSmallerPairs(nums, low);
}
int countSmallerPairs(vector<int>&nums, int th)
{
TrieNode* root = new TrieNode();
int count = 0;
for (int num: nums)
{
count += countSmallerThan(root, num, th);
insert(root, num);
}
return count;
}
int countSmallerThan(TrieNode* root, int num, int th)
{
auto node = root;
int count = 0;
for (int i=31; i>=0; i--)
{
int c = (th>>i)&1;
int b = (num>>i)&1;
int a = c ^ b;
if (a == 1 && c == 1)
{
if (node->next[0]) count += node->next[0]->cnt;
if (node->next[1]) node = node->next[1];
else break;
}
else if (a==1 && c==0)
{
if (node->next[1]) node = node->next[1];
else break;
}
else if (a==0 && c==1)
{
if (node->next[1]) count += node->next[1]->cnt;
if (node->next[0]) node = node->next[0];
else break;
}
else if (a==0 && c==0)
{
if (node->next[0]) node = node->next[0];
else break;
}
}
return count;
}
void insert(TrieNode* root, int num)
{
auto node = root;
for (int i=31; i>=0; i--)
{
if ((num>>i)&1)
{
if (node->next[1]==NULL)
node->next[1] = new TrieNode();
node->next[1]->cnt++;
node = node->next[1];
}
else
{
if (node->next[0]==NULL)
node->next[0] = new TrieNode();
node->next[0]->cnt++;
node = node->next[0];
}
}
}
};