-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3.Building_Roads.cpp
More file actions
80 lines (72 loc) · 1.49 KB
/
3.Building_Roads.cpp
File metadata and controls
80 lines (72 loc) · 1.49 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
// Problem is asking for disconnected components and how we can connect them.
#include<bits/stdc++.h>
using namespace std;
#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define nl '\n'
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
const int MN = 1e5 + 10;
vector<int>g[MN];
bool vis[MN];
int rep[MN];
int n, m;
// void dfs(int v) {
// vis[v] = true;
// for (auto x : g[v]) {
// if (!vis[x])dfs(x);
// }
// }
void dfs(int v) {
vis[v] = true;
for (auto x : g[v]) {
if (!vis[x])dfs(x);
}
}
int count_component() {
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
rep[cnt++] = i;
dfs(i);
}
}
return cnt;
}
// int count_component() {
// int cnt = 0;
// for (int i = 1; i <= n; i++) {
// if (!vis[i]) {
// rep[cnt++] = i;
// dfs(i);
// }
// }
// return cnt;
// }
void solve() {
// int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++) {
int x, y; cin >> x >> y;
g[x].push_back(y); g[y].push_back(x);
}
int b = count_component();
cout << b - 1 << nl;
for (int i = 1; i < b; i++) {
cout << rep[i - 1] << " " << rep[i] << " ";
}
}
int main()
{
IOS;
// Windows env
#ifndef ONLINE_JUDGE
freopen("input.txt", "r" , stdin);
freopen("output.txt", "w", stdout);
#endif
// int t; cin >> t;
// while (t--)
// {
// solve();
// }
solve();
}