-
Notifications
You must be signed in to change notification settings - Fork 2
/
connected_components.cpp
63 lines (55 loc) · 1.37 KB
/
connected_components.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
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// TC: O(E+V), undirected graph
///////////////////// start yanking ////////////////////
vector<vector<ll>> graph;
vector<bool> visited;
void build(ll n) { // call me (initialization)
graph.resize(n+1);
visited.resize(n+1);
}
void insert_edge(ll s, ll d) { // call me (building)
graph[s].push_back(d);
}
void __dfs(ll start, vector<ll> &cdfs) {
visited[start] = true;
cdfs.push_back(start);
for (ll i = 0; i < graph[start].size(); i++) {
if (!visited[graph[start][i]]) {
__dfs(graph[start][i], cdfs);
}
}
}
vector<vector<ll>> connected_components() { // call me (result)
vector<vector<ll>> cc;
vector<ll> cdfs;
for (ll i = 1; i < graph.size(); i++) {
if (!visited[i]) {
__dfs(i, cdfs);
cc.push_back(cdfs);
cdfs.clear();
}
}
return cc;
}
///////////////////// stop yanking /////////////////////
int main() {
ll v, e, s, d;
cin >> v;
build(v); // called
cin >> e;
for (ll i = 0; i < e; i++) {
cin >> s >> d;
insert_edge(s, d); // called
insert_edge(d, s); // called
}
auto cc = connected_components(); // called
for (auto &_cc : cc) {
for (auto &c : _cc) {
cout << c << " ";
}
cout << "\n";
}
return 0;
}