HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
👻
개발 기록
/
코딩테스트 스터디
코딩테스트 스터디
/
Minimum Fuel Cost to Report to the Capital

Minimum Fuel Cost to Report to the Capital

Link
https://leetcode.com/problems/Minimum-Fuel-Cost-to-Report-to-the-Capital/
Deadline
Feb 28, 2023
Status
Archived
Type
Tree
DFS
BFS

문제

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.
Example 1:
notion image
Input: roads = [[0,1],[0,2],[0,3]], seats = 5 Output: 3 Explanation: - Representative1 goes directly to the capital with 1 liter of fuel. - Representative2 goes directly to the capital with 1 liter of fuel. - Representative3 goes directly to the capital with 1 liter of fuel. It costs 3 liters of fuel at minimum. It can be proven that 3 is the minimum number of liters of fuel needed.
Example 2:
notion image
Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2 Output: 7 Explanation: - Representative2 goes directly to city 3 with 1 liter of fuel. - Representative2 and representative3 go together to city 1 with 1 liter of fuel. - Representative2 and representative3 go together to the capital with 1 liter of fuel. - Representative1 goes directly to the capital with 1 liter of fuel. - Representative5 goes directly to the capital with 1 liter of fuel. - Representative6 goes directly to city 4 with 1 liter of fuel. - Representative4 and representative6 go together to the capital with 1 liter of fuel. It costs 7 liters of fuel at minimum. It can be proven that 7 is the minimum number of liters of fuel needed.
Example 3:
notion image
Input: roads = [], seats = 1 Output: 0 Explanation: No representatives need to travel to the capital city.
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

풀이

재영
const makeGraph = (roads) => { const graph = new Array(roads.length + 1).fill().map(() => []); roads.forEach(([city1, city2]) => { graph[city1].push(city2); graph[city2].push(city1); }); return graph; }; const checkGoTogether = (total, seats) => total <= seats; const dfs = (graph, visited, root, liter, depth, seats, isRoot) => { visited[root] = true; if (graph[root].length === 1 && !isRoot) {// Leaf인 경우 return { liter: 0, cars: 1, cnt: 1 }; // 백트래킹 } const nowLiter = liter; const nowSeats = seats; const nowDepth = depth; let cars = 1; let nowCnt = 1; // 해당 함수 컨텍스트 상에서 좌석을 채운 사람 수 for (const nextCity of graph[root]) { if (visited[nextCity]) continue; const { liter: childLiter, cars: childCars, cnt: childCnt, } = dfs(graph, visited, nextCity, nowLiter, nowDepth + 1, nowSeats, false); if (checkGoTogether(nowCnt + childCnt, seats)) { cars += childCars - 1; nowCnt += childCnt; } else { cars += childCars; nowCnt = nowCnt + childCnt - seats; // 차를 하나 더 탔으니까 } liter += childCars + childLiter; } return { liter, cars, cnt: nowCnt }; }; /** * @param {number[][]} roads * @param {number} seats * @return {number} */ const minimumFuelCost = (roads, seats) => { const graph = makeGraph(roads); const visited = new Array(roads.length + 1).fill(false); return dfs(graph, visited, 0, 0, 0, seats, true).liter; };
 
답변들을 보고 최적화를 진행했습니다…!
세상에는 똑똑한 사람들이 많군요 🙆🏻🙆🏻‍♀️
const makeGraph = (roads) => { const graph = new Array(roads.length + 1).fill().map(() => []); roads.forEach(([city1, city2]) => { graph[city1].push(city2); graph[city2].push(city1); }); return graph; }; /** * @param {number[][]} roads * @param {number} seats * @return {number} */ const minimumFuelCost = (roads, seats) => { const graph = makeGraph(roads); let cost = 0; // visited가 없으므로 방문여부를 탐색할 것을 찾아야 함 -> parent와 node와 비교 const dfs = (node, parent) => { let people = 1; for (const nextCity of graph[node]) { // 밑까지 내려가는 과정 if (nextCity === parent) continue; const childPeople = dfs(nextCity, node); people += childPeople; } if (parent === null) { return cost; // 다 올라온 경우 } else { cost += Math.ceil(people / seats); return people; // 밑까지 다 간다음 올라가는 과정이라 생각하면 돼요 } }; return dfs(0, null); };
은찬
const minimumFuelCost = function(roads, seats) { let answer = 0; const n = roads.length; const path = Array.from({length: n + 1}, () => []); const dfs = (start, from) => { let countOfPeople = 1; for(const to of path[start]) { if(to !== from) { countOfPeople += dfs(to, start); } } if(start !== 0) { answer += Math.ceil(countOfPeople / seats); } return countOfPeople; } for(let road of roads) { const [a, b] = road; path[a].push(b); path[b].push(a); } dfs(0, 0); return answer; };