forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
72 lines (57 loc) · 1.54 KB
/
main2.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/// Source : https://leetcode.com/problems/course-schedule-ii/
/// Author : liuyubobobo
/// Time : 2018-12-16
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/// Using Queue is enough
/// Since we are only interested in 0-indegree vertex :-)
///
/// Time Complexity: O(E)
/// Space Complexity: O(V + E)
class Solution {
public:
vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {
vector<int> pre(numCourses, 0);
vector<vector<int>> g(numCourses);
for(const pair<int, int>& p: prerequisites){
int from = p.second;
int to = p.first;
g[from].push_back(to);
pre[to] ++;
}
queue<int> q;
for(int i = 0; i < numCourses; i ++)
if(pre[i] == 0)
q.push(i);
vector<int> res;
while(!q.empty()){
int id = q.front();
q.pop();
res.push_back(id);
for(int next: g[id]){
pre[next] --;
if(pre[next] == 0)
q.push(next);
}
}
if(res.size() == numCourses)
return res;
return {};
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<pair<int, int>> pre1 = {{1,0}};
print_vec(Solution().findOrder(2, pre1));
// 0 1
vector<pair<int, int>> pre2 = {{1,0},{2,0},{3,1},{3,2}};
print_vec(Solution().findOrder(4, pre2));
// 0 1 2 3
return 0;
}