Advertisement
Tarche

CSES-BuildingRoads

Jun 8th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. //Lucas Hernán Tarche, 4to 4ta Turno Tarde, ESCCP
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. vector<vector<int>> ady;
  8. vector<bool> visited;
  9.  
  10. vector<pair<int, int>> res;
  11.  
  12. void dfs(int node) {
  13.     if(visited[node]) return;
  14.     visited[node] = true;
  15.     for (auto edge : ady[node]) {
  16.         dfs(edge);
  17.     }
  18. }
  19.  
  20. int main() {
  21.     int N, M, u, v;
  22.     cin >> N >> M;
  23.     ady.resize(N+1);
  24.     visited.resize(N+1);
  25.     for (int i = 0; i < M; i++) {
  26.         cin >> u >> v;
  27.         ady[u].push_back(v);
  28.         ady[v].push_back(u);
  29.     }
  30.  
  31.     dfs(1);
  32.  
  33.     for (int i = 2; i <= N; i++) {
  34.         if (!visited[i]) {
  35.             res.push_back({1, i});
  36.             dfs(i);
  37.             ady[1].push_back(i);
  38.             ady[i].push_back(1);
  39.         }
  40.     }
  41.  
  42.     cout << (int)res.size() << endl;
  43.     for (auto edge : res){
  44.         cout << edge.first << " " << edge.second << endl;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement