
Sponsored
Sponsored
This approach involves topologically sorting the courses based on their prerequisites and then calculating the minimal time to complete each course using dynamic programming.
(a,b) is a directed edge from a to b.Time Complexity: O(n + E), where n is the number of courses and E is the number of prerequisite relationships, due to traversing all nodes and edges once.
Space Complexity: O(n + E), needed to store the graph and additional arrays.
1```csharp
2using System;
3using System.Collections.Generic;
4
5public class ParallelCourses {
6 public static int MinTime(int n, int[][] relations, int[] time) {
7 var adj = new List<int>[n + 1];
8 var indegree = new int[n + 1];
9 var dp = new int[n + 1];
10
11 for (int i = 0; i <= n; i++)
12 adj[i] = new List<int>();
13
14 foreach (var relation in relations) {
int u = relation[0], v = relation[1];
adj[u].Add(v);
indegree[v]++;
}
var queue = new Queue<int>();
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
queue.Enqueue(i);
dp[i] = time[i - 1];
}
}
while (queue.Count > 0) {
int u = queue.Dequeue();
foreach (var v in adj[u]) {
dp[v] = Math.Max(dp[v], dp[u] + time[v - 1]);
indegree[v]--;
if (indegree[v] == 0) {
queue.Enqueue(v);
}
}
}
int maxTime = 0;
for (int i = 1; i <= n; i++)
maxTime = Math.Max(maxTime, dp[i]);
return maxTime;
}
public static void Main() {
int n = 5;
int[][] relations = new int[][] { new int[] { 1,5 }, new int[] { 2,5 }, new int[] { 3,5 }, new int[] { 3,4 }, new int[] { 4,5 } };
int[] time = new int[] { 1, 2, 3, 4, 5 };
Console.WriteLine(MinTime(n, relations, time)); // Output: 12
}
}
```The C# solution makes use of the C# collections, employing lists to maintain adjacency information and tracking of indegrees. Upon performing a topological sort assisted by a queue, it uses a dynamic programming table to calculate the minimum completion time.
This approach uses Depth-First Search (DFS) with memorization to efficiently compute the completion time for courses.
Time Complexity: O(n + E), visiting each node and edge at least once.
Space Complexity: O(n + E), due to storage for graph data and function call stack.
```The Java solution conducts DFS to determine each course's minimal completion time, storing the results in a dp array to speed up computations. Using this technique, we can compute the maximum time needed to complete all courses efficiently.