-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtopological.cpp
More file actions
72 lines (62 loc) · 1.28 KB
/
topological.cpp
File metadata and controls
72 lines (62 loc) · 1.28 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
#include<bits/stdc++.h>
using namespace std;
vector < vector <int> > adj;
int V,E,dfstime;
int discover[110],finished[110],parent[110];
bool marked[110];
struct node{
int info;
node *next;
node(int k){
info = k;
next = NULL;
}
}*root;
node * insert(int k){
if(root == NULL)
return new node(k);
node *x = new node(k);
x->next = root;
return x;
}
void dfsvisit(int s)
{
discover[s] = ++dfstime;
marked[s] = 1;
for(auto v:adj[s])
if(!marked[v])
dfsvisit(v);
finished[s] = ++dfstime;
root = insert(s);
}
void dfs()
{
for(int i = 1; i < V+1; ++i)
parent[i] = -1,marked[i] = 0;
dfstime = 0;
for(int i = 1; i < V+1; ++i){
if(!marked[i])
dfsvisit(i);
}
}
int main()
{
cin>>V>>E;
adj.resize(V+10);
for(int i = 0; i < E; ++i){
int x,y; cin>>x>>y;
adj[x].push_back(y);
}
dfs();
for(int i = 0; i < V+1; ++i)
cout<<discover[i]<<(i==V?'\n':' ');
for(int i = 0; i < V+1; ++i)
cout<<finished[i]<<(i==V?'\n':' ');
node *x = root;
// linked list consists topologically sorted vertices
while(x != NULL){
cout<<x->info<<(x->next==NULL?'\n':' ');
x = x->next;
}
return 0;
}