-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfstopologicalsorting.cpp
More file actions
51 lines (48 loc) · 1.13 KB
/
dfstopologicalsorting.cpp
File metadata and controls
51 lines (48 loc) · 1.13 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
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int V, E;
void dfs(int u, vector<vector<int>> &graph, vector<bool> &visited, vector<int> &result)
{
visited[u] = true;
for (int i = 0; i < graph[u].size(); i++)
{
int v = graph[u][i];
if (!visited[v])
{
dfs(v, graph, visited, result);
}
}
result.push_back(u);
}
void topologicalsort(vector<vector<int>> &graph, vector<int> &result)
{
vector<bool> visited(V, false);
for (int i = 0; i < V;i++)
if (!visited[i])
{
dfs(i, graph, visited, result);
}
reverse(result.begin(), result.end());
}
int main()
{
freopen("topologicalsorting.inp", "r", stdin);
freopen("topologicalsorting.out", "w", stdout);
vector<vector<int>> graph;
vector<int> result;
cin >> V >> E;
graph.assign(V+1, vector<int>());
for (int u, v, i = 0; i < E; i++)
{
cin >> u >> v;
graph[u].push_back(v);
}
topologicalsort(graph, result);
for (int i = 0; i < V; i++)
{
cout << result[i] << " " << endl;
}
return 0;
}