1494. Parallel Courses II
Description
You are given an integer n
, which indicates that there are n
courses labeled from 1
to n
. You are also given an array relations
where relations[i] = [prevCoursei, nextCoursei]
, representing a prerequisite relationship between course prevCoursei
and course nextCoursei
: course prevCoursei
has to be taken before course nextCoursei
. Also, you are given the integer k
.
In one semester, you can take at most k
courses as long as you have taken all the prerequisites in the previous semesters for the courses you are taking.
Return the minimum number of semesters needed to take all courses. The testcases will be generated such that it is possible to take every course.
Example 1:
Input: n = 4, relations = [[2,1],[3,1],[1,4]], k = 2 Output: 3 Explanation: The figure above represents the given graph. In the first semester, you can take courses 2 and 3. In the second semester, you can take course 1. In the third semester, you can take course 4.
Example 2:
Input: n = 5, relations = [[2,1],[3,1],[4,1],[1,5]], k = 2 Output: 4 Explanation: The figure above represents the given graph. In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester. In the second semester, you can take course 4. In the third semester, you can take course 1. In the fourth semester, you can take course 5.
Constraints:
1 <= n <= 15
1 <= k <= n
0 <= relations.length <= n * (n-1) / 2
relations[i].length == 2
1 <= prevCoursei, nextCoursei <= n
prevCoursei != nextCoursei
- All the pairs
[prevCoursei, nextCoursei]
are unique. - The given graph is a directed acyclic graph.
Solution
parallel-courses-ii.py
class Solution:
def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:
pre = [0] * n
paths = [n + 1] * (1 << n)
target = (1 << n) - 1
for x, y in relations:
x -= 1
y -= 1
pre[y] |= (1 << x)
queue = deque([(0, 0)])
while queue:
state, steps = queue.popleft()
new_courses = []
for i in range(n):
if (state & pre[i]) != pre[i]: continue
if state & (1 << i) > 0: continue
new_courses.append(i)
if len(new_courses) <= k:
for course in new_courses:
state |= (1 << course)
if state == target: return 1 + steps
if steps + 1 < paths[state]:
queue.append((state, steps + 1))
paths[state] = steps + 1
else:
for comb in combinations(new_courses, k):
new_state = state
for course in list(comb):
new_state |= (1 << course)
if steps + 1 < paths[new_state]:
queue.append((new_state, steps + 1))
paths[new_state] = steps + 1
parallel-courses-ii.cpp
class Solution {
int a[15],f[32768],o[32768];
public:
int minNumberOfSemesters(int n, vector<vector<int>>& dependencies, int k) {
memset(a,0,sizeof(a));
int i,j,l;
for(auto e:dependencies)a[e[1]-1]|=1<<e[0]-1;
for(i=1;i<1<<n;i++)o[i]=o[i>>1]+(i&1);
memset(f,127,sizeof(f));
for(i=f[0]=0;i<1<<n;i++)if(f[i]<=n)
{
for(j=l=0;j<n;j++)if(!(i>>j&1)&&(a[j]&i)==a[j])l|=1<<j;
for(j=l;j;j=j-1&l)if(o[j]<=k)f[i|j]=min(f[i|j],f[i]+1);
}
return f[(1<<n)-1];
}
};