Reorder Routes to Make All Paths Lead to City Zero

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

There are n cities numbered from 0 to n - 1 and n - 1 roads such that there is only one way to travel between two different cities (this network forms a tree). Last year, the ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [a_i, b_i] represents a road from city a_i to city b_i.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task is to reorient some roads such that each city can reach city 0. Return the minimum number of edges that need to be reversed.

It is guaranteed that each city can reach city 0 after reordering.

Examples

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]

Output: 3

Explanation: We need to reverse the roads [0,1], [1,3], and [4,5] so that every city can reach city 0.

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]

Output: 2

Explanation: We need to reverse the roads [1,2] and [3,4] so that every city can reach city 0.

Input: n = 3, connections = [[1,0],[2,0]]

Output: 0

Explanation: All roads already point toward city 0, so no reversals are needed.

Constraints

  • 2 <= n <= 5 * 10^4
  • connections.length == n - 1
  • connections[i].length == 2
  • 0 <= a_i, b_i <= n - 1
  • a_i != b_i
Source: Graphs pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle