-
Notifications
You must be signed in to change notification settings - Fork 0
/
Building_Roads.cpp
49 lines (48 loc) · 923 Bytes
/
Building_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
#include<bits/stdc++.h>
using namespace std;
#define int long long
vector<int>adj[100001];
vector<bool>visited(100001,false);
vector<int>head;//head of the connected components of the graph
void dfs(int node)
{
visited[node]=true;
for(auto child:adj[node])
{
if(!visited[child])
{
dfs(child);
}
}
}
void sol()
{
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++)
{
int a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for(int i=1;i<=n;++i)
{
//if the node is not visited then it is the head of the connected component of the graph
if(!visited[i])
{
head.push_back(i);
dfs(i);
}
}
cout<<head.size()-1<<endl;
for(int i=0;i<head.size()-1;++i)
{
cout<<head[i]<<" "<<head[i+1]<<endl;
}
}
signed main()
{
sol();
return 0;
}