MicrosoftOA #58
Reorder Routes to Make All Paths Lead to the City Zero
Estimated MediumJudge-ready
Topics (AI-labelled)Union-Find
The underlying undirected graph is a tree, and each edge is currently one-way. Edges may be reversed so that every city can reach the capital, city 0. Find the minimum number of reversals.
This site uses a standard input/output protocol.
Input
The first line contains N (2..50000), followed by N−1 lines a b, each meaning a→b; 0≤a,b<N, a≠b, and the underlying graph is guaranteed to be a tree.
Output
Output a single integer, the answer.
Example 1
Input:
6
0 1
1 3
2 3
4 0
4 5
Output:
3
Example 2
Input:
5
1 0
1 2
3 2
3 4
Output:
2
Example 3
Input:
3
1 0
2 0
Output:
0
Example notes
Example 1: 0→1, 1→3, and 4→5 must be reversed, for 3 in total. Example 2: 1→2 and 3→4 must be reversed, for 2 in total. Example 3: every edge already points toward 0, so 0 reversals.
Editorial
Loading solution…