Orange Farm Simulation
Time limit10sMemory limit1024 MB
For each road in a tree of fields, find the largest XOR of competitiveness values between a field on one side and a field on the other side after cutting that road.
- Level
Hard8 of 10
- Topics
- Tree, Trie, Bit manipulation, DFS
- Solved
- No attempts yet
Problem
Bru is playing an orange farm simulation game. After playing for a long time, Bru has built orange fields on the farm, and the fields are connected by roads so that every field can be reached from every other field.

As the farm grows, Bru wants to cut one road to split the farm in two. Splitting the farm lets both halves grow at the same time, so efficiency goes up. However, once the farm is split, the fields on opposite sides enter a competitive relationship. Field has competitiveness . If field and field are in a competitive relationship, the competition index between them is , where is bitwise XOR. The total competition index for cutting one road is the maximum competition index over all competitive pairs created by that cut.
For example, take the farm in the figure above with , and cut the road between fields 2 and 3, as in the figure below.

The competition indices of all competitive pairs are:
- Field 3 with fields 1, 2, 4, and 7: 2, 1, 7, 4
- Field 5 with fields 1, 2, 4, and 7: 4, 7, 1, 2
- Field 6 with fields 1, 2, 4, and 7: 7, 4, 2, 1
The maximum is 7, so the total competition index for cutting the road between fields 2 and 3 is 7.
Write a program that computes the total competition index for cutting each road.
Input
The first line contains the number of fields .
The second line contains the competitiveness of each field, .
From the third line to line , line contains the numbers of the two fields and joined by road , in the form .
Output
Print the total competition index for cutting each road, from road 1 to road , one per line, in order.
Constraints
- Every field can be reached from every other field through the given roads.