-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.go
73 lines (69 loc) · 1.18 KB
/
Solution.go
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
type Trie struct {
children [2]*Trie
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(x int) {
node := this
for i := 47; i >= 0; i-- {
v := (x >> i) & 1
if node.children[v] == nil {
node.children[v] = newTrie()
}
node = node.children[v]
}
}
func (this *Trie) search(x int) int {
node := this
res := 0
for i := 47; i >= 0; i-- {
v := (x >> i) & 1
if node == nil {
return res
}
if node.children[v^1] != nil {
res = res<<1 | 1
node = node.children[v^1]
} else {
res <<= 1
node = node.children[v]
}
}
return res
}
func maxXor(n int, edges [][]int, values []int) int64 {
g := make([][]int, n)
for _, e := range edges {
a, b := e[0], e[1]
g[a] = append(g[a], b)
g[b] = append(g[b], a)
}
s := make([]int, n)
var dfs1 func(i, fa int) int
dfs1 = func(i, fa int) int {
t := values[i]
for _, j := range g[i] {
if j != fa {
t += dfs1(j, i)
}
}
s[i] = t
return t
}
dfs1(0, -1)
ans := 0
tree := newTrie()
var dfs2 func(i, fa int)
dfs2 = func(i, fa int) {
ans = max(ans, tree.search(s[i]))
for _, j := range g[i] {
if j != fa {
dfs2(j, i)
}
}
tree.insert(s[i])
}
dfs2(0, -1)
return int64(ans)
}