Editorial
For an incidence of vertex and edge , let be the parity of the number of edges incident to that were inspected before . Edge incurs its cost exactly when
At a vertex of degree , local ranks are , so exactly incidences have value . Conversely, any chosen incident edges can occupy the second, fourth, and later even positions.
For a tree, arbitrary local edge orders at all vertices can always be merged into one global order. If the union of all local precedence constraints contained a directed cycle, the line-graph structure of a tree would force that cycle to lie inside the clique belonging to one original vertex. That clique is oriented by a linear order and is acyclic, a contradiction.
The problem is therefore a static optimization: at every vertex , choose exactly
incidences with value .
Root the tree. Let be the minimum subtree cost when the value on 's side of its parent edge is . For a child joined by edge , if the value on 's side is , define
Start with for every child. Then add the smallest values of .
Sorting the deltas at every vertex gives time and memory.
Solution written by GPT5