-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroads.cpp
54 lines (42 loc) · 956 Bytes
/
roads.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
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pi = pair<ll, ll>;
using vi = vector<ll>;
ll n, m;
vector<set<int>> adj;
vector<bool> visited;
void dfs(int node) {
if (visited[node]) return;
visited[node] = true;
for(int child : adj[node]) {
dfs(child);
}
}
int main() {
cin >> n >> m;
adj = vector<set<int>>(n, set<int>{});
visited = vector<bool>(n, 0);
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
x--, y--;
adj[x].insert(y);
adj[y].insert(x);
}
// dfs for connected components
vector<int> repr;
int sum = 0;
for (int i = 0; i < n; i++) {
if(!visited[i]) {
sum++;
repr.emplace_back(i + 1);
dfs(i);
}
}
cout << sum - 1 << endl;
for(int i = 1; i < repr.size(); i++) {
cout << repr[i] << ' ' << repr[i - 1] << endl;
}
return 0;
}