|
| 1 | +/** |
| 2 | + * 2477. Minimum Fuel Cost to Report to the Capital |
| 3 | + * https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a tree (i.e., a connected, undirected graph with no cycles) structure country network |
| 7 | + * consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is |
| 8 | + * city 0. You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there |
| 9 | + * exists a bidirectional road connecting cities ai and bi. |
| 10 | + * |
| 11 | + * There is a meeting for the representatives of each city. The meeting is in the capital city. |
| 12 | + * |
| 13 | + * There is a car in each city. You are given an integer seats that indicates the number of seats |
| 14 | + * in each car. |
| 15 | + * |
| 16 | + * A representative can use the car in their city to travel or change the car and ride with another |
| 17 | + * representative. The cost of traveling between two cities is one liter of fuel. |
| 18 | + * |
| 19 | + * Return the minimum number of liters of fuel to reach the capital city. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + *@param {number[][]} roads |
| 24 | + *@param {number} seats |
| 25 | + *@return {number} |
| 26 | + */ |
| 27 | +varminimumFuelCost=function(roads,seats){ |
| 28 | +constn=roads.length+1; |
| 29 | +constgraph=Array.from({length:n},()=>[]); |
| 30 | +for(const[a,b]ofroads){ |
| 31 | +graph[a].push(b); |
| 32 | +graph[b].push(a); |
| 33 | +} |
| 34 | + |
| 35 | +letfuel=0; |
| 36 | +dfs(0,-1); |
| 37 | +returnfuel; |
| 38 | + |
| 39 | +functiondfs(node,parent){ |
| 40 | +letrepresentatives=1; |
| 41 | +for(constneighborofgraph[node]){ |
| 42 | +if(neighbor!==parent){ |
| 43 | +representatives+=dfs(neighbor,node); |
| 44 | +} |
| 45 | +} |
| 46 | +if(node!==0){ |
| 47 | +fuel+=Math.ceil(representatives/seats); |
| 48 | +} |
| 49 | +returnrepresentatives; |
| 50 | +} |
| 51 | +}; |