This question evaluates understanding of directed versus undirected graph representations, tree rooting, and optimization of edge orientations, testing competency in graph algorithms and tree re-rooting reasoning.
You are given a connected graph with n nodes labeled 0..n-1 and n-1 directed edges. If you ignore directions, the edges form a tree (i.e., the underlying undirected graph is a tree).
You may pick any node r as the root. You are allowed to reverse the direction of any edge; reversing one edge costs 1.
Your goal is to choose a root r and reverse as few edges as possible so that, in the final directed tree, every edge points away from the root (equivalently: for every node v != r, the unique path from r to v follows edge directions from parent to child).
n
edges
, where each edge is a pair
(u, v)
meaning a directed edge
u -> v
Return the minimum number of edge reversals needed over all choices of root r.
1 <= n <= 2 * 10^5
len(edges) = n - 1
If n = 3 and edges = [(0,1), (2,0)]:
0
requires reversing
(2,0)
to
(0,2)
→ cost
1
2
requires reversing
(0,1)
and
(2,0)
? (check orientation away from 2) → higher
So the answer is
1
.