[LeetCode] Minimum Fuel Cost to Report to the Capital

2477. Minimum Fuel Cost to Report to the Capital

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
int dfs(int u, int par, vector<vector<int>>& adj, int dep, long long & res, int& s) {
int now = 1;
for(auto v : adj[u]) {
if(v == par) continue;
now += dfs(v,u,adj,dep + 1, res,s);
if(now >= s) {
res += dep;
now -= s;
}
}
if(now > 0 and u != 0) res += 1;
return now;
}
public:
long long minimumFuelCost(vector<vector<int>>& roads, int seats) {
long long res = 0, n = roads.size() +1;
vector<vector<int>> adj(n);
for(auto r : roads) {
int u = r[0], v = r[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(0,-1,adj,0,res, seats);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/20/PS/LeetCode/minimum-fuel-cost-to-report-to-the-capital/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.