2477. 到达首都的最少油耗

2477. 到达首都的最少油耗

解法一: 深度优先遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
func minimumFuelCost(roads [][]int, seats int) int64 {
n := len(roads)
trees := make([][]int, n + 1)
for _, road := range roads {
trees[road[0]] = append(trees[road[0]], road[1])
trees[road[1]] = append(trees[road[1]], road[0])
}
var ans int64 = 0
var dfs func (son, parent int) int
dfs = func (son, parent int) int {
count := 0
for _, tree := range trees[son] {
if tree != parent {
curCount := dfs(tree, son) + 1
count += curCount
ans += int64((curCount + seats - 1) / seats)
}
}
return count
}
dfs(0, -1)
return ans
}
作者

wuhunyu

发布于

2023-12-05

更新于

2023-12-05

许可协议