Microsoft

Anonymous User
394
Oct 18, 2025

The country is modeled as a directed graph with g_nodes cities (nodes numbered 1 to g_nodes) and g_nodes - 1 uni-directional edges (roads). The edges are given by arrays g_from and g_to, where the i-th edge is directed from g_from[i] to g_to[i]. The underlying undirected graph is a tree (connected and acyclic).
For each city i (1 ≤ i ≤ g_nodes), compute the minimum number of edge reversals required so that there is a directed path from i to every other city. In other words, orient the edges (by possibly reversing some) to form an arborescence rooted at i.
Return an array of size g_nodes where the i-th element (0-based) is the result for city i+1.
Example:

Input: g_nodes = 4, g_from = [1,2,3], g_to = [4,4,4]
Output: [2, 2, 2, 3]

Explanation:

For root 1: Reverse edges 2→4 and 3→4 (2 reversals).
For root 2: Reverse edges 1→4 and 3→4 (2 reversals).
For root 3: Reverse edges 1→4 and 2→4 (2 reversals).
For root 4: Reverse all three edges (3 reversals).

Comments (2)