-
Notifications
You must be signed in to change notification settings - Fork 0
/
Topology_Sort_with_DFS.cpp
68 lines (56 loc) · 1.09 KB
/
Topology_Sort_with_DFS.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
const int maxn = 5000+50;
vector<int> adj[maxn];
stack<int> ans;
int state[maxn];
bool head[maxn];
bool valid;
int n, m;
void dfs(int src)
{
state[src] = 1;
for (auto next : adj[src])
if (!state[next]) dfs(next);
else if (state[next] == 1){
// 有環
valid = false;
return;
}
state[src] = 2;
ans.push(src);
}
void topology_sort()
{
for (int i = 0; i < n; i++){
// 從 (0 ~ n-1) 找一個頭沒有被任何人連到的開始做dfs
if (valid && head[i]) dfs(i);
}
if (!valid)
{
cout << "Cycle!" << endl;
return;
}
while (!ans.empty())
{
cout << ans.top() << endl;
ans.pop();
}
}
int main()
{
cin >> n >> m;
memset(head, true, sizeof(head));
// make adjcent list
for (int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
head[b] = false;
//
adj[a].push_back(b);
}
memset(state, 0, sizeof(state));
valid = true;
//如果 valid = false代表有還
topology_sort();
return 0;
}