-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtopsort.cpp
More file actions
54 lines (47 loc) · 988 Bytes
/
topsort.cpp
File metadata and controls
54 lines (47 loc) · 988 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> g;
vector<int> color;
bool cycle = false;
vector<int> path;
void dfs (int v) {
color[v] = 1;
for (auto i = g[v].begin(); i != g[v].end(); i++) {
if (color[*i] == 0) {
dfs(*i);
}
else if (color[*i] == 1) {
cycle = true;
}
}
color[v] = 2;
path.push_back(v);
}
int main() {
freopen("topsort.in", "r", stdin);
freopen("topsort.out", "w", stdout);
int n, m;
cin >> n >> m;
g.resize(n);
color.resize(n, 0);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
--x, --y;
g[x].push_back(y);
}
for (int i = 0; i < n; i++) {
if (color[i] == 0) {
dfs(i);
}
}
if (cycle) {
cout << "-1";
return 0;
}
for (int i = (int) path.size() - 1; i >= 0; i--) {
cout << path[i] + 1 << " ";
}
return 0;
}