File tree Expand file tree Collapse file tree 1 file changed +88
-0
lines changed
Trie/1803.Count-Pairs-With-XOR-in-a-Range Expand file tree Collapse file tree 1 file changed +88
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ class TrieNode
3+ {
4+ public:
5+ TrieNode* next[2 ];
6+ int cnt;
7+ TrieNode ()
8+ {
9+ for (int i=0 ; i<2 ; i++)
10+ next[i] = NULL ;
11+ cnt=0 ;
12+ }
13+ };
14+ public:
15+ int countPairs (vector<int >& nums, int low, int high)
16+ {
17+ return countSmallerPairs (nums, high+1 ) - countSmallerPairs (nums, low);
18+ }
19+
20+ int countSmallerPairs (vector<int >&nums, int th)
21+ {
22+ TrieNode* root = new TrieNode ();
23+ int count = 0 ;
24+ for (int num: nums)
25+ {
26+ count += countSmallerThan (root, num, th);
27+ insert (root, num);
28+ }
29+ return count;
30+ }
31+
32+ int countSmallerThan (TrieNode* root, int num, int th)
33+ {
34+ auto node = root;
35+ int count = 0 ;
36+ for (int i=31 ; i>=0 ; i--)
37+ {
38+ int c = (th>>i)&1 ;
39+ int b = (num>>i)&1 ;
40+ int a = c ^ b;
41+ if (a == 1 && c == 1 )
42+ {
43+ if (node->next [0 ]) count += node->next [0 ]->cnt ;
44+ if (node->next [1 ]) node = node->next [1 ];
45+ else break ;
46+ }
47+ else if (a==1 && c==0 )
48+ {
49+ if (node->next [1 ]) node = node->next [1 ];
50+ else break ;
51+ }
52+ else if (a==0 && c==1 )
53+ {
54+ if (node->next [1 ]) count += node->next [1 ]->cnt ;
55+ if (node->next [0 ]) node = node->next [0 ];
56+ else break ;
57+ }
58+ else if (a==0 && c==0 )
59+ {
60+ if (node->next [0 ]) node = node->next [0 ];
61+ else break ;
62+ }
63+ }
64+ return count;
65+ }
66+
67+ void insert (TrieNode* root, int num)
68+ {
69+ auto node = root;
70+ for (int i=31 ; i>=0 ; i--)
71+ {
72+ if ((num>>i)&1 )
73+ {
74+ if (node->next [1 ]==NULL )
75+ node->next [1 ] = new TrieNode ();
76+ node->next [1 ]->cnt ++;
77+ node = node->next [1 ];
78+ }
79+ else
80+ {
81+ if (node->next [0 ]==NULL )
82+ node->next [0 ] = new TrieNode ();
83+ node->next [0 ]->cnt ++;
84+ node = node->next [0 ];
85+ }
86+ }
87+ }
88+ };
You can’t perform that action at this time.
0 commit comments