-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdfs+bfs.h
More file actions
88 lines (76 loc) · 1.81 KB
/
Copy pathdfs+bfs.h
File metadata and controls
88 lines (76 loc) · 1.81 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
88
#ifndef INCLUDE
#include "include.h"
#endif
struct graph {
vec<bool> used;
vec<vec<int>> edges;
vec<int> d_out;
int n;
graph(int n) : n(n) {
used.assign(n + 1, {});
edges.assign(n + 1, {});
//d_out.assign(n + 1, {});
}
void read(int k) {
while (k--) {
int x, y; cin >> x >> y;
edges[x].push_back(y);
edges[y].push_back(x);
}
}
void read_tree_by_ancestors() {
for (int i = 2; i <= n; ++i) {
int x; cin >> x;
edges[i].push_back(x);
edges[x].push_back(i);
}
}
void dfs(int s) {
used[s] = true;
for (auto v : edges[s])
if (!used[v])
dfs(v);
}
void bfs(int s) {
queue<int> q;
q.push(s);
used[s] = true;
d_out[s] = 0;
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto v : edges[u])
if (!used[v])
{
q.push(v);
used[v] = true;
d_out[v] = d_out[u] + 1;
}
}
}
auto new_dfs(int s) {
used.assign(n + 1, {});
return dfs(s);
}
auto new_bfs(int s) {
used.assign(n + 1, {});
return bfs(s);
}
void add(int x, int y) {
edges[x].push_back(y);
edges[y].push_back(x);
}
int countEdges() {
int sum = 0;
for (auto edgesx : edges)
sum += edgesx.size();
return sum / 2;
}
friend auto &operator<<(ostream &os, const graph &g) {
for (int i = 0; i < g.edges.size(); ++i)
for (auto &j : g.edges[i])
if (i < j)
os << i << " " << j << "\n";
return os;
}
};