Loading...

10-18 leetcode 2050

链接 2050. Parallel Courses III

题目

You are given an integer n, which indicates that there are n courses labeled from 1 to n. You are also given a 2D integer array relations where relations[j] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.

You must find the minimum number of months needed to complete all the courses following these rules:

You may start taking a course at any time if the prerequisites are met.
Any number of courses can be taken at the same time.
Return the minimum number of months needed to complete all the courses.

Note: The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).

题解

这题我的手段是先建图,求出每个点的入度后,BFS 求满足所有课程的值就行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from collections import defaultdict, deque


class Solution:
def minimumTime(self, n: int, relations: list[list[int]], time: list[int]) -> int:
graph = defaultdict(list)
in_degree = defaultdict(int)
for prev, current in relations:
graph[prev].append(current)
in_degree[current] += 1
roots = list(filter(lambda x: in_degree[x] == 0, range(1, n + 1)))
distance = [0] + time
queue = deque(roots)
while queue:
current_course = queue.popleft()
for next_course in graph[current_course]:
distance[next_course] = max(
distance[next_course],
distance[current_course] + time[next_course - 1],
)
in_degree[next_course] -= 1
if in_degree[next_course] == 0:
queue.append(next_course)
return max(distance)

Comment