Avatar CS Knowledge Wiki

多叉树遍历

题目描述Leetcode周赛6243. Minimum Fuel Cost to Report to the CapitalThere is a tree (i.e., a connected, undirected graph with no cycles) structure countr...

Leetcode周赛6243. 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.

Example 1:

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.
plaintext

Example 2:

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.
plaintext

思路#

考虑每条边上至少需要多少辆车。

以 0 为根,设子树 x 的大小为 size\textit{size},那么它到它父节点这条边的「流量」是,那么就至少需要 ⌈sizeseats⌉\left\lceil\dfrac{\textit{size}}{\textit{seats}}\right\rceil 辆车。

求解向上取整的时候有个tick: ceil(x/a) = (x + a - 1)/a。

累加除了 x=0x=0以外的值,就是答案。

这里需要注意的是,题目给出的是全部的边,我们应该根据边构建出图的临接表达,方便DFS搜索遍历。

代码#

复杂度分析#

  • 时间复杂度:O(n)O(n),其中 nn 为 roads\textit{roads} 的长度。
  • 空间复杂度:O(n)O(n)。
Knowledge map

知识图谱

当前文档、同目录指南与引用关系。

准备中 全局图谱

正在构建知识图谱...

拖动节点 · 滚动缩放 · 点击打开

帮助与支持

这篇文档有帮助吗?

请给我们反馈以改进文档质量
(点击按钮后会打开邮箱)

帮助改进文档

所有文档均开源,发现问题或不清楚的地方?提交 PR 来帮助改进。

编辑此页面 了解如何贡献 →

需要更多帮助?

加入社区或直接联系获取支持

文件管理器 /
位置 /
内容
Knowledge explorer

知识图谱

全部知识 准备图谱...
文章 文档 标签 分类

正在加载知识网络...

拖动节点 · 滚动缩放 · 单击查看详情 · 双击打开页面
标签云 / Tag Cloud