-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCourse_Schedule.cpp
More file actions
97 lines (81 loc) · 2.1 KB
/
Course_Schedule.cpp
File metadata and controls
97 lines (81 loc) · 2.1 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
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
vector<int> findOrder(int V, int m, vector<vector<int>> prerequisites)
{
vector<int> adj[V];
for(auto it : prerequisites)
{
adj[it[1]].push_back(it[0]);
}
int indegree[V] = {0};
for(int i = 0; i < V; i++)
{
for(auto it : adj[i])
indegree[it]++;
}
queue<int>q;
for(int i = 0; i < V; i++)
{
if(indegree[i] == 0)
q.push(i);
}
vector<int> topo;
while(!q.empty())
{
int node = q.front();
q.pop();
topo.push_back(node);
for(auto it : adj[node])
{
indegree[it]--;
if(indegree[it] == 0) q.push(it);
}
}
if(topo.size() == V) return topo;
return {};
}
};
//{ Driver Code Starts.
int check(int V, vector <int> &res, vector<int> adj[]) {
vector<int> map(V, -1);
for (int i = 0; i < V; i++) {
map[res[i]] = i;
}
for (int i = 0; i < V; i++) {
for (int v : adj[i]) {
if (map[i] > map[v]) return 0;
}
}
return 1;
}
int main() {
int T;
cin >> T;
while (T--) {
int n, m;
cin >> n >> m;
int u, v;
vector<vector<int>> prerequisites;
for (int i = 0; i < m; i++) {
cin >> u >> v;
prerequisites.push_back({u,v});
}
vector<int> adj[n];
for (auto pre : prerequisites)
adj[pre[1]].push_back(pre[0]);
Solution obj;
vector <int> res = obj.findOrder(n, m, prerequisites);
if(!res.size())
cout<<"No Ordering Possible"<<endl;
else
cout << check(n, res, adj) << endl;
}
return 0;
}
// } Driver Code Ends