LC.P2050[并行课程III]

方法一:拓扑排序+动态规划

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
35
class Solution {
public int minimumTime(int n, int[][] relations, int[] time) {
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
int[] in = new int[n];
for (int[] e : relations) {
int a = e[0] - 1, b = e[1] - 1;
g[a].add(b);
++in[b];
}
Deque<Integer> queue = new ArrayDeque<>();
// f[i] 表示节点 i 的最早完成时间
int[] f = new int[n];
int ans = 0;
for (int i = 0; i < n; ++i) {
int v = in[i], t = time[i];
if (v == 0) {
queue.offer(i);
f[i] = t;
ans = Math.max(ans, t);
}
}
while (!queue.isEmpty()) {
int i = queue.poll();
for (int j : g[i]) {
f[j] = Math.max(f[j], f[i] + time[j]);
ans = Math.max(ans, f[j]);
if (--in[j] == 0) {
queue.offer(j);
}
}
}
return ans;
}
}
  • 时间复杂度:$O(m + n)$
  • 空间复杂度:$O(m + n)$