Given a graph and an integer $k$, where the nodes represent values, we can choose an edge, and perform XOR operations on its nodes corresponding to $k$. The goal is the find the maximum sum of the values after 0 or more XOR operations.
Intuition
Since XOR operations satisfies the property that a XOR b XOR b = a, we can record the gain after XOR operation on an edge and finally obtain the result.
Approach
We use total_sum to record the sum of the values of the original trees.
Then for each node, we perform the XOR operation and record the change if the change > 0, and this change requires one operation, which we add to count. Meanwhile, we use positive_min and negative_max to record the minimum absolute change for reverting use.
Now after all nodes are computed, we need to compute the result.
- If
countis even, it means the operations satisfied the requirement that the nodes of an edge changes simultaneously - If
countis odd, then there is one invalid operation and we need to revert the operation. To make the final sum maximum, we can either subtract thepositive_minor addnegative_max, the result is then obtained by taking the maximum of them.
Complexity
- $$O(n)$$
- $$O(1)$$
Code
| |