-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTask_II_9.cpp
More file actions
87 lines (72 loc) · 1.4 KB
/
Task_II_9.cpp
File metadata and controls
87 lines (72 loc) · 1.4 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <list>
#include <vector>
using namespace std;
vector< list<int> > graph = {
{ 1 }, // a 0
{ 2, 4, 5 }, // b 1
{ 3, 6 }, // c 2
{ 2, 7 }, // d 3
{ 5, 0 }, // e 4
{ 6 }, // f 5
{ 5 }, // g 6
{ 3, 6 } // h 7
};
vector< list <int> > TransGraph(const vector< list <int> >& graph) {
vector< list <int> > result(graph.size());
for (size_t i = 0; i < graph.size(); ++i) {
for (const auto& el : graph[i]) {
result[el].push_back(i);
}
}
return result;
}
vector< list <int> > graphTrans = TransGraph(graph);
vector<bool> used(graph.size());
vector <int> order, component;
void dfs(int v) {
used[v] = true;
for (auto l : graph[v]) {
int to = l;
if (!used[to]) {
dfs(to);
}
}
order.push_back(v);
}
void topologicalSort() {
for (size_t i = 0; i < graph.size(); ++i) {
used[i] = false;
}
order.clear();
for (size_t i = 0; i < graph.size(); ++i) {
if (!used[i]) {
dfs(i);
}
}
reverse(begin(order), end(order));
}
void dfs2(int v) {
used[v] = true;
component.push_back(v);
for (auto l : graphTrans[v]) {
if (!used[l])
dfs2(l);
}
}
int main() {
topologicalSort();
used.assign(graph.size(), false);
for (size_t i = 0; i < graph.size(); ++i) {
int v = order[graph.size() - 1 - i];
if (!used[v]) {
dfs2(v);
for (auto l : component)
cout << l << ' ';
component.clear();
}
}
cout << endl;
system("pause");
return 0;
}