-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind the ordering of tasks from given dependencies.cpp
More file actions
78 lines (69 loc) · 1.56 KB
/
Copy pathFind the ordering of tasks from given dependencies.cpp
File metadata and controls
78 lines (69 loc) · 1.56 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
/*
1
3 3
0 1
0 2
1 2
*/
#include<bits/stdc++.h>
using namespace std;
class Graph{
private:
int n;
list<int> *arr;
int *indegree;
void _topological(vector<int> &vec, int visited[]){
if(vec.size() == n){
for(int i = 0; i < n; i++)
cout << vec[i] << " ";
cout << endl;
return;
}
for(int i = 0; i < n; i++){
if(indegree[i] == 0 && visited[i] == 0){
visited[i] = 1;
vec.push_back(i);
for(auto it = arr[i].begin(); it != arr[i].end(); it++)
indegree[*it]--;
_topological(vec, visited);
vec.pop_back();
for(auto it = arr[i].begin(); it != arr[i].end(); it++)
indegree[*it]++;
visited[i] = 0;
}
}
}
public:
Graph(int n){
this->n = n;
arr = new list<int>[n];
indegree = new int[n];
for(int i = 0; i < n; i++)
indegree[i] = 0;
}
void addEdge(int u, int v){
arr[u].push_back(v);
indegree[v]++;
}
void topologicalSort(){
vector<int> vec;
int visited[n];
memset(visited, 0, sizeof(visited));
_topological(vec, visited);
}
};
int main(){
int t, n, e;
cin >> t;
while(t--){
cin >> n >> e;
Graph g(n);
for(int i = 0; i < e; i++){
int a, b;
cin >> a >> b;
g.addEdge(a, b);
}
g.topologicalSort();
}
return 0;
}