-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207.Course Schedule
More file actions
37 lines (37 loc) · 1.3 KB
/
Copy path207.Course Schedule
File metadata and controls
37 lines (37 loc) · 1.3 KB
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
34
35
36
37
class Solution {
public:
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int>post2pre(numCourses,0);
vector<unordered_set<int>> pre2post(numCourses);
for(int i=0; i<prerequisites.size();i++){
pre2post[prerequisites[i].second].insert(prerequisites[i].first);
}
for(int i=0; i<numCourses;i++){
for(auto itr=pre2post[i].begin();itr!=pre2post[i].end();itr++){
post2pre[*itr]++;
}
}
queue<int> candidate;
for(int i=0;i<numCourses;i++){
if(post2pre[i]==0)
candidate.push(i);
}
int finishCourse=0;
while(!(candidate).empty()){
int num=candidate.front();
candidate.pop();
finishCourse++;
for(auto itr1=pre2post[num].begin();itr1!=pre2post[num].end();itr1++){
int post=*itr1;
post2pre[post]--;
if(post2pre[post]==0){
candidate.push(post);
} // ¸üÐÂpost2pre±í,ÒÔ±ãÏ´ÎÈ¡Êý½øres
}
//pre2post.erase(num);
}
if(finishCourse<numCourses)
return false;
return true;
}
};