class Solution:
def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
indegree = collections.defaultdict(int)
m = collections.defaultdict(set)
for a, b in relations:
a, b = a-1, b-1 # convert to 0 based
m[a].add(b)
indegree[b] += 1
# find the 0 indegree nodes
q = []
cost = [0] * n # months required to finish i course, it is the max cost of predecessor nodes + time[i]
for i in range(n):
if indegree[i] == 0:
q.append(i)
cost[i] = time[i]
while q:
node = q.pop(0)
for v in m[node]:
cost[v] = max(cost[v], cost[node] + time[v])
indegree[v] -= 1
if indegree[v] == 0:
q.append(v)
return max(cost)
444. Sequence Reconstruction
class Solution:
def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:
nodes = set([node for seq in seqs for node in seq])
graph = {node : [] for node in nodes}
indegree = {node:0 for node in nodes} # 图,从上往下只能有一条路线 每次从indegree = 0 的点走 如果有2个或者以上Indgree=0的就是false, 走了这个indegree=0的点,它下面的点的indegree就-1
for seq in seqs:
for i in range(len(seq)-1):
pre = seq[i]
nxt = seq[i+1]
graph[pre].append(nxt)
indegree[nxt] += 1
# find the indegree = 0 one, which is the root, should only ha