Skip to content

Commit 6901a48

Browse files
authored
Create 2479-maximum-xor-of-two-non-overlapping-subtrees.js
1 parent 0cc33a3 commit 6901a48

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
class TrieNode {
2+
constructor() {
3+
this.next = [null, null]
4+
}
5+
}
6+
const bigIntMinAndMax = (...args) => {
7+
return args.reduce(
8+
([min, max], e) => {
9+
return [e < min ? e : min, e > max ? e : max]
10+
},
11+
[args[0], args[0]],
12+
)
13+
}
14+
/**
15+
* @param {number} n
16+
* @param {number[][]} edges
17+
* @param {number[]} values
18+
* @return {number}
19+
*/
20+
const maxXor = function (n, edges, values) {
21+
const ins = new Solution()
22+
return Number(ins.maxXor(n, edges, values))
23+
}
24+
25+
class Solution {
26+
constructor() {
27+
this.next = []
28+
this.val = []
29+
this.values = []
30+
this.root = null
31+
this.ret = 0n
32+
}
33+
34+
insert(num) {
35+
let node = this.root
36+
num = BigInt(num)
37+
for (let i = 63n; i >= 0n; i--) {
38+
const d = (num >> i) & 1n
39+
if (node.next[d] === null) {
40+
node.next[d] = new TrieNode()
41+
}
42+
node = node.next[d]
43+
}
44+
}
45+
46+
find(num) {
47+
num = BigInt(num)
48+
let node = this.root
49+
if (this.root.next[0] === null && this.root.next[1] === null) {
50+
return 0
51+
}
52+
let ret = 0n
53+
for (let i = 63n; i >= 0n; i--) {
54+
const d = (num >> i) & 1n
55+
if (node.next[1n - d] !== null) {
56+
ret += 1n << i
57+
node = node.next[1n - d]
58+
} else {
59+
ret += 0n
60+
node = node.next[d]
61+
}
62+
}
63+
return ret
64+
}
65+
66+
maxXor(n, edges, values) {
67+
this.values = values
68+
for (let i = 0; i < n; i++) {
69+
this.next[i] = []
70+
}
71+
for (let i = 0; i < edges.length; i++) {
72+
const [a, b] = edges[i]
73+
this.next[a].push(b)
74+
this.next[b].push(a)
75+
}
76+
this.root = new TrieNode()
77+
this.dfs(0, -1)
78+
this.dfs2(0, -1)
79+
return this.ret
80+
}
81+
82+
dfs(cur, parent) {
83+
let v = this.values[cur]
84+
for (let i = 0; i < this.next[cur].length; i++) {
85+
const nxt = this.next[cur][i]
86+
if (nxt === parent) continue
87+
v += this.dfs(nxt, cur)
88+
}
89+
this.val[cur] = v
90+
return v
91+
}
92+
93+
dfs2(cur, parent) {
94+
for (let i = 0; i < this.next[cur].length; i++) {
95+
const nxt = this.next[cur][i]
96+
if (nxt === parent) continue
97+
this.ret = bigIntMinAndMax(this.ret, this.find(this.val[nxt]))[1]
98+
this.dfs2(nxt, cur)
99+
this.insert(this.val[nxt])
100+
}
101+
}
102+
}

0 commit comments

Comments
 (0)