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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#define MAX_CITIES 100000
6
7// Adjacency list
8int tree[MAX_CITIES][MAX_CITIES];
9int child_count[MAX_CITIES];
10int visited[MAX_CITIES];
11
12int dfs(int node, int seats) {
13 visited[node] = 1;
14 int totalFuel = 0;
15 for (int i = 0; i < child_count[node]; ++i) {
16 int next = tree[node][i];
17 if (!visited[next]) {
18 int people = dfs(next, seats);
19 totalFuel += (people + seats - 1) / seats;
20 totalFuel += people; // Adding people to fuel calculation
21 }
22 }
23 return totalFuel + 1;
24}
25
26int minimumFuelCost(int roads[][2], int roadsSize, int seats) {
27 for (int i = 0; i < roadsSize; ++i) {
28 int a = roads[i][0];
29 int b = roads[i][1];
30 tree[a][child_count[a]++] = b;
31 tree[b][child_count[b]++] = a;
32 }
33 return dfs(0, seats) - 1; // Subtract 1 as node 0 doesn't use fuel
34}
35
36int main() {
37 int roads[5][2] = {{3,1},{3,2},{1,0},{0,4},{0,5},{4,6}};
38 int seats = 2;
39 printf("%d\n", minimumFuelCost(roads, 5, seats));
40 return 0;
41}
This C solution uses a depth-first search to calculate the minimum number of liters needed. It creates an adjacency list from the input nodes and applies DFS to compute two things: the total number of people at each node (along with its subtree) and the fuel cost for moving them to the capital.
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.
1
The Python solution constructs an adjacency list and uses a queue for BFS traversal, ensuring we're adding necessary roles to a full potential delegation. Consequently, each BFS iteration accounts for the fuel needed by constraining nodes via BFS into a specific directional queue.