leetcode 1136

问题

There are N courses, labelled from 1 to N.

We are given relations[i] = [X, Y], representing a prerequisite relationship between course X and course Y: course X has to be studied before course Y.

In one semester you can study any number of courses as long as you have studied all the prerequisites for the course you are studying.

Return the minimum number of semesters needed to study all courses. If there is no way to study all the courses, return -1.

Example 1:

img

1
2
3
4
Input: N = 3, relations = [[1,3],[2,3]]
Output: 2
Explanation:
In the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.

Example 2:

img

1
2
3
4
Input: N = 3, relations = [[1,2],[2,3],[3,1]]
Output: -1
Explanation:
No course can be studied because they depend on each other.

Note:

  1. 1 <= N <= 5000
  2. 1 <= relations.length <= 5000
  3. relations[i][0] != relations[i][1]
  4. There are no repeated relations in the input.

分析

拓扑排序

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int minimumSemesters(int N, vector<vector<int>>& relations) {
vector<vector<int>> e(N+1);
vector<int> deg(N+1); // in deg
for (vector<int> r: relations) {
e[r[0]].push_back(r[1]);
deg[r[1]]++;
}

queue<int> q;
for (int i = 1; i <= N; ++i) {
if (deg[i] == 0)q.push(i);
}

int ans = 0;
int num = 0;
while (q.size()) {
ans++;
num += q.size();
int size = q.size();
while (size--) {
int x = q.front();
q.pop();
for (int y: e[x]) {
if (--deg[y] == 0) q.push(y);
}
}
}
if (num != N) return -1;
return ans;
}
};