Sponsored
Sponsored
Using Depth-First Search (DFS), we can traverse the tree from the capital city '0' and calculate the minimum fuel cost required to gather all representatives in the capital city. We need to propagate the number of representatives from child nodes towards the root (capital) while managing the representatives getting into available seats effectively.
Time Complexity: O(n), where n is the number of cities as we visit each edge once.
Space Complexity: O(n), due to the storage used for the adjacency list and recursion stack.
1def minimumFuelCost(roads, seats):
2 from collections import defaultdict
3
4 adjList = defaultdict(list)
5 visited = set()
6
7 def dfs(node):
8 visited.add(node)
9 total_rep = 1
10 for neighbor in adjList[node]:
11 if neighbor not in visited:
12 reps = dfs(neighbor)
13 nonlocal cost
14 cost += (reps + seats - 1) // seats
15 total_rep += reps
16 return total_rep
17
18 for a, b in roads:
19 adjList[a].append(b)
20 adjList[b].append(a)
21
22 cost = 0
23 dfs(0)
24 return cost
25
26roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]]
27seats = 2
28print(minimumFuelCost(roads, seats))
This Python solution uses a DFS approach to traverse a graph from the capital node and compute the cost of fuel based on representatives. Recursion effectively manages graph traversal while non-local values track consumption of fuel according to available seats in the car.
By utilizing Breadth-First Search (BFS), we can tackle this problem iteratively, processing nodes level by level from the capital outward. Track the representatives as they move towards the capital and the fuel cost incrementally.
Time Complexity: O(n) based on visiting each node.
Space Complexity: O(n) for queue storage.
1using System.Collections.Generic;
class Solution {
public static long MinimumFuelCost(int[][] roads, int seats) {
int n = roads.Length + 1;
List<int>[] adjList = new List<int>[n];
for (int i = 0; i < n; ++i) adjList[i] = new List<int>();
foreach (var road in roads) {
adjList[road[0]].Add(road[1]);
adjList[road[1]].Add(road[0]);
}
bool[] visited = new bool[n];
Queue<(int node, int reps)> q = new Queue<(int, int)>();
q.Enqueue((0, 0));
visited[0] = true;
long cost = 0;
while (q.Count > 0) {
var (node, reps) = q.Dequeue();
int max_reps = reps + 1;
long nodeFuel = (max_reps + seats - 1) / seats;
cost += nodeFuel;
foreach (int neighbor in adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.Enqueue((neighbor, max_reps));
}
}
}
return cost;
}
static void Main() {
int[][] roads = { new int[]{0,1}, new int[]{0,2}, new int[]{0,3} };
int seats = 5;
Console.WriteLine(MinimumFuelCost(roads, seats));
}
}
The above C# code solution implements BFS within a queue to explore the adjacency list of cities hierarchically. It calculates minimum fuel expenditure by leveraging iterable manipulation over representatives connecting to capital.