Minimum Fuel Cost to Report to the Capital - Problem

There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0.

You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

There is a meeting for the representatives of each city. The meeting is in the capital city.

There is a car in each city. You are given an integer seats that indicates the number of seats in each car.

A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.

Return the minimum number of liters of fuel to reach the capital city.

Input & Output

Example 1 — Basic Tree
$ Input: roads = [[0,1],[0,2],[0,3]], seats = 5
Output: 3
💡 Note: Capital 0 connects to cities 1, 2, 3. Each city sends 1 representative, each needs 1 car (since 1 ≤ 5 seats). Total: 1 + 1 + 1 = 3 liters.
Example 2 — Limited Seats
$ Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
Output: 7
💡 Note: Tree structure requires multiple cars due to seat limitation. Representatives share rides optimally based on subtree sizes and seat capacity.
Example 3 — Single Road
$ Input: roads = [[0,1]], seats = 1
Output: 1
💡 Note: Only city 1 needs to send representative to capital 0. One car travels the single road: 1 liter.

Constraints

  • 1 ≤ n ≤ 105
  • roads.length == n - 1
  • roads[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • roads represents a valid tree
  • 1 ≤ seats ≤ 105

Visualization

Tap to expand
Minimum Fuel Cost to Report to the Capital INPUT Tree Structure (Country Network) 0 Capital 1 2 3 Input Values roads = [[0,1],[0,2],[0,3]] seats = 5 n = 4 cities Each car has 5 seats ALGORITHM STEPS 1 Build Adjacency List Create graph from roads 2 DFS from Capital Traverse tree, count people 3 Calculate Cars Needed ceil(people / seats) 4 Sum Fuel Costs Each car uses 1 fuel/edge DFS Calculation Edge People Cars Fuel 1-->0 1 1 1 2-->0 1 1 1 3-->0 1 1 1 Total Fuel: 3 FINAL RESULT All Representatives Travel to Capital 0 Capital (Meeting) 1L 1L 1L OUTPUT 3 liters of fuel OK - Minimum fuel achieved! Key Insight: DFS traverses from leaves to root. For each edge, count people in subtree and calculate cars needed: ceil(people/seats). Each car crossing an edge costs 1 fuel. Ride sharing minimizes total cars by combining passengers. Formula: fuel += ceil(subtree_size / seats) TutorialsPoint - Minimum Fuel Cost to Report to the Capital | DFS with Ride Sharing Approach
Asked in
Google 25 Amazon 20 Microsoft 15
35.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen