Advertisement
tepyotin2

Building Roads

May 11th, 2025
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n, m;
  6. vector<int> adj[100001];
  7. vector<int> start;
  8. bool visited[100001];
  9.  
  10. void dfs(int node){
  11.     if(visited[node]) return;
  12.     visited[node] = true;
  13.     for(auto v: adj[node]){
  14.         if(!visited[v]){
  15.             dfs(v);
  16.         }
  17.     }
  18. }
  19.  
  20. int main(){
  21.     //freopen("buildingroads.in", "r", stdin);
  22.    
  23.     cin >> n >> m;
  24.     for(int i=0; i<m; i++){
  25.         int a, b;
  26.         cin >> a >> b;
  27.         adj[a].push_back(b);
  28.         adj[b].push_back(a);
  29.     }
  30.     for(int i=1; i<=n; i++){
  31.         if(!visited[i]){
  32.             start.push_back(i);
  33.             dfs(i);
  34.         }
  35.     }
  36.     cout << start.size()-1 << '\n';
  37.     for(int i=1; i<start.size(); i++){
  38.         cout << start[0] << " " << start[i] << '\n';
  39.     }
  40.    
  41.     return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement