1646. Two Disjoint Branches XOR
A company's reporting chart has n staff numbered 0..n-1; person 0 is the top boss and edges lists the n - 1 reporting links (each pair [u, v] joins a manager and a direct report, in either order). Person i brings in values[i] revenue, and a person's team total is the sum of values over that person and everyone below them.
Choose two different people such that neither is a boss (direct or indirect) of the other. Their score is the bitwise XOR of the two team totals. Return the largest score possible, or 0 if no such pair of people exists. The result needs a 64-bit integer.
The efficient idea is a depth-first walk with a binary trie: when entering a person, query the trie holding the totals of every person already finished, and insert a person's total when leaving them. Use O(n log V) time and O(n log V) space, and keep the traversal iterative.
Example 1
- Input:
- n = 5edges = [[0,1],[0,2],[1,3],[1,4]]values = [1,2,4,8,16]
- Output:
- 30
- Explanation:
Subtree sums are 31, 26, 4, 8, 16; nodes 2 and 4 are unrelated and 4 XOR 16 = 20, but nodes 1 and 2 (26 and 4) give 30, the best.
Example 2
- Input:
- n = 4, edges = [[0,1],[1,2],[2,3]], values = [5,6,7,8]
- Output:
- 0
- Explanation:
The tree is a chain, so every pair of nodes is ancestor-related and the answer is 0.
Example 3
- Input:
- n = 4, edges = [[0,1],[0,2],[0,3]], values = [1,3,5,6]
- Output:
- 6
- Explanation:
Leaves have sums 3, 5 and 6; the best pair is 3 XOR 5 = 6 or 5 XOR 6 = 3 or 3 XOR 6 = 5, so the maximum is 6.
Constraints
2 ≤ n ≤ 10000
1 ≤ values[i] ≤ 109 (team totals stay below 246)
edges has n - 1 pairs [u, v] describing a tree on nodes 0..n-1, rooted at node 0
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms
Expected complexity
- Time
- O(n log V)
- Space
- O(n log V)