-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathordenacao-topologica-2.cpp
72 lines (57 loc) · 1.25 KB
/
ordenacao-topologica-2.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
69
70
71
72
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#define MAX 100000
#define UNVISITED -1
using namespace std;
int component[MAX],
grau[MAX];
vector<int> grafo[MAX],
orderedTop;
/**
*
* Graph is unweighted,
* or all distances are one between two vertices adjacent.
*
*/
// Deep First Search
void dfs(int v)
{
component[v] = 1;
// For every neighboor of v
for(int i = 0; i < grafo[v].size(); ++i)
{
if(component[grafo[v][i]] == UNVISITED)
{
// mark as visited
// explore neighboors
dfs(grafo[v][i]);
}
}
orderedTop.push_back(v);
}
int main() {
int n, m, v, a, b;
// the vertice is marked as 1 to n
cin >> n >> m;
// Building list adjacent
for(int i = 0; i < m; ++i) {
cin >> a >> b;
grafo[a].push_back(b);
grau[b] += 1;
}
memset(component, UNVISITED, sizeof component);
for(int i = 1; i <= n; ++i) {
if(component[i] == UNVISITED)
dfs(i);
}
if(orderedTop.size() < n) {
cout << "Impossivel\n";
return 0;
}
for(int i = n - 1; i >= 0; --i) {
cout << orderedTop[i] << endl;
}
return 0;
}