LC.P2477[到达首都的最少油耗]

方法一:DFS

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
28
29
30
31
32
33
34
class Solution {
List<Integer>[] g;
int seats;
long ans;

public long minimumFuelCost(int[][] roads, int seats) {
this.seats = seats;
int n = roads.length + 1;
g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
for (int[] road : roads) {
int a = road[0], b = road[1];
g[a].add(b);
g[b].add(a);
}
dfs(0, -1);
return ans;
}

private int dfs(int x, int pa) {
int size = 1;
for (int y : g[x]) {
// 递归子节点,统计子树大小
if (y != pa) {
size += dfs(y, x);
}
}
// x 不是根节点
if (x > 0) {
ans += (size - 1) / seats + 1;
}
return size;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$