【LetMeFly】1462. Curriculum IV: Topological Sorting
Leetcode question link: https://leetcode.cn/problems/course-schedule-iv/
You need to take a total of numCourses
courses, and the course numbers are in 0
order numCourses-1
. You will get an array prerequisite
that indicates that if you want to choose a course, you must choose a course first.prerequisites[i] = [ai, bi]
bi
ai
- Some courses will have direct prerequisite courses. For example, if you want to take a course
1
, you must take the course first0
, then[0,1]
the number of pairs of prerequisite courses will be given in the form of pairs.
Prerequisites can also be indirect . If course a
is b
a prerequisite for course , and course b
is c
a prerequisite for course , then course a
is c
a prerequisite for course .
You also get an array queries
with . For query , you should answer whether the course is a prerequisite for the course.queries[j] = [uj, vj]
j
uj
vj
Returns a Boolean array answer
where answer[j]
is j
the answer to the query.
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]], queries = [[0,1],[1,0]] Output: [false,true] Explanation: Course 0 is not a prerequisite course for Course 1, However, Course 1 is a prerequisite course for Course 0.
Example 2:
Input: numCourses = 2, prerequisites = [], queries = [[1,0],[0,1]] Output: [false,false] Explanation: There are no prerequisite course pairs, so each course is independent .
Example 3:
Input: numCourses = 3, prerequisites = [[1,2],[1,0],[2,0]], queries = [[1,0],[1,2]] Output: [ true ,true]
hint:
2 <= numCourses <= 100
0 <= prerequisites.length <= (numCourses * (numCourses - 1) / 2)
prerequisites[i].length == 2
0 <= ai, bi <= n - 1
ai != bi
- every pair is different
[ai, bi]
- There are no rings in the prerequisite diagram.
0 <= ui, vi <= n - 1
ui != vi
Method 1: Topological sorting
First of all, in terms of determining the sequence of courses, this question is similar to LeetCode 207. Curriculum , which can be solved using topological sorting .
So, the question is for 1 0 4 10^4104 queries, how to quickly return each query?
We can create a num C ourses × num C ourses numCourses\times numCoursesnumCourses×Array of boolean type n u m C o u rses is P re isPreisPre。 i s P r e [ a ] [ b ] isPre[a][b] i s P re [ a ] [ b ] represents courseaaWhether a is course bbPrerequisite courses for b . (In this way, for a certain queryqqq , just returnis P re [ q [ 0 ] ] [ q [ 1 ] ] isPre[q[0]][q[1]]i s P re [ q [ 0 ]] [ q [ 1 ]] can be)
In topological sorting, if it is determined that thisCourse is a prerequisite course for nextCourse, then all prerequisite courses for thisCourse will be prerequisite courses for nextCourse . Expressed as a formula:
∀ 0 ≤ i ≤ n u m C o u r s e s , i s P r e [ i ] [ n e x t C o u r s e ] ∣ = i s P r e [ i ] [ t h i s C o u r s e ] \forall 0\leq i\leq numCourses,\ \ isPre[i][nextCourse]\ \ |=\ isPre[i][thisCourse] ∀0≤i≤numCourses, isPre[i][nextCourse] ∣= isPre[i][thisCourse]
- Time complexity O ( num Courses 2 + n + q ) O(numCourses^2 + n + q)O(numCourses2+n+q ) , wherennn is the prerequisite course relationship coefficient,qqq is the number of queries
- Space complexity O ( num Courses 2 + n ) O(numCourses^2 + n)O(numCourses2+n)
AC code
C++
class Solution {
public:
vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) {
// 建图
vector<vector<int>> graph(numCourses);
vector<int> indegree(numCourses);
for (vector<int>& ab : prerequisites) {
graph[ab[0]].push_back(ab[1]);
indegree[ab[1]]++;
}
// 初始化队列
queue<int> q;
for (int i = 0; i < numCourses; i++) {
if (!indegree[i]) {
q.push(i);
}
}
// 预处理(拓扑排序)
vector<vector<bool>> isPre(numCourses, vector<bool>(numCourses, false));
while (q.size()) {
int thisCourse = q.front();
q.pop();
for (int nextCourse : graph[thisCourse]) {
indegree[nextCourse]--;
if (!indegree[nextCourse]) {
q.push(nextCourse);
}
isPre[thisCourse][nextCourse] = true;
for (int i = 0; i < numCourses; i++) {
isPre[i][nextCourse] = isPre[i][nextCourse] | isPre[i][thisCourse]; // vector不支持|=
}
}
}
// 查询
vector<bool> ans;
for (vector<int>& q : queries) {
ans.push_back(isPre[q[0]][q[1]]);
}
return ans;
}
};
Python
# from typing import List
class Solution:
def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:
graph = [[] for _ in range(numCourses)]
indegree = [0] * numCourses
for a, b in prerequisites:
graph[a].append(b)
indegree[b] += 1
q = []
for i in range(numCourses):
if not indegree[i]:
q.append(i)
isPre = [[False for _ in range(numCourses)] for __ in range(numCourses)]
while q:
thisCourse = q.pop()
for nextCourse in graph[thisCourse]:
indegree[nextCourse] -= 1
if not indegree[nextCourse]:
q.append(nextCourse)
isPre[thisCourse][nextCourse] = True
for i in range(numCourses):
isPre[i][nextCourse] |= isPre[i][thisCourse]
ans = []
for a, b in queries:
ans.append(isPre[a][b])
return ans
The article is published simultaneously on CSDN. It is not easy to be original. Please attach the link to the original article after reprinting with the author's consent ~
Tisfy: https://letmefly.blog.csdn.net/article/details/132825649