Graph Theory37 sections · 1633 units
Open in Course

Parallel Courses III - Implementation

The code

Here's the solution:

function minimumTime(n, relations, time):
    adj := array of lists, size n + 1
    indegree := array of size n + 1, initialized to 0
    finishTime := copy of time array (1-indexed)
    queue := empty queue

    for each [prev, next] in relations:
        add next to adj[prev]
        indegree[next] := indegree[next] + 1

    for i from 1 to n:
        if indegree[i] = 0 then
            push i to queue

    while queue is not empty:
        u := pop from queue
        for each v in adj[u]:
            finishTime[v] := max(finishTime[v], finishTime[u] + time[v])
            indegree[v] := indegree[v] - 1
            if indegree[v] = 0 then
                push v to queue

    return max(finishTime)

Time: O(V+E)O(V + E). Space: O(V+E)O(V + E).