-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path2050-parallel-courses-iii.py
59 lines (51 loc) · 1.81 KB
/
2050-parallel-courses-iii.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from heapq import *
class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = [[] for _ in range(n)]
indegrees = [0 for _ in range(n)]
for p, q in relations:
p -= 1
q -= 1
graph[p].append(q)
indegrees[q] += 1
heap = []
for i, indegree in enumerate(indegrees):
if indegree == 0:
heappush(heap, (time[i], i))
while heap:
prev, node = heappop(heap)
for neighbor in graph[node]:
indegrees[neighbor] -= 1
if indegrees[neighbor] == 0:
heappush(heap, (prev + time[neighbor], neighbor))
return prev
# time O(VlogV)
# space O(V+E)
# using graph and kahn and topological sort and heap
from collections import deque
class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
graph = [[] for _ in range(n)]
indegrees = [0 for _ in range(n)]
for p, q in relations:
p -= 1
q -= 1
graph[p].append(q)
indegrees[q] += 1
costs = [0 for _ in range(n)]
queue = deque([])
for i, indegree in enumerate(indegrees):
if indegree == 0:
queue.append(i)
costs[i] = time[i]
while queue:
node = queue.popleft()
for neighbor in graph[node]:
indegrees[neighbor] -= 1
costs[neighbor] = max(costs[neighbor], costs[node] + time[neighbor])
if indegrees[neighbor] == 0:
queue.append(neighbor)
return max(costs)
# time O(V+E)
# space O(V+E)
# using graph and kahn and topological sort and dp