Advertisement
shawon_majid

building roads

Jun 5th, 2022
771
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. //Bismillahir Rahman-ir Rahim
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. #define debug(x) cout << '>' << #x << " : " << x << endl;
  5. #define all(c) c.begin(), c.end()
  6. #define F first
  7. #define S second
  8. #define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
  9. typedef unsigned long long ull;
  10. typedef long long ll;
  11.  
  12. vector < int > adj[100006];
  13. int vis[100006]; // 0
  14. //
  15. // unordered_map < int, vector <int > > adj;
  16.  
  17. void bfs(int source){
  18.  
  19.     queue < int > q;
  20.     q.push(source);
  21.     vis[source] = 1;
  22.     // level[source] = 0;
  23.  
  24.     // cout << source << endl;
  25.  
  26.     while(!q.empty()){
  27.         int u = q.front();
  28.         q.pop();
  29.         for(int i = 0; i < adj[u].size(); i++){
  30.             int v = adj[u][i];
  31.             if(!vis[v]){
  32.                 vis[v] = 1;
  33.                 // level[v] = level[u] + 1;
  34.                 // cout << v << endl;
  35.                 q.push(v);
  36.             }
  37.         }
  38.     }
  39.  
  40. }
  41.  
  42.  
  43. int main(){
  44.  
  45.     int n, e;
  46.     cin >> n >> e;
  47.  
  48.     // memset(vis, 0, sizeof vis);
  49.  
  50.     for(int i = 0; i < e; i++){
  51.         int a, b;
  52.         cin >> a >> b;
  53.         adj[a].push_back(b);
  54.         adj[b].push_back(a);
  55.     }
  56.  
  57.     int cnt = 0;
  58.     vector < int > ans;
  59.     for(int i = 1; i <= n; i++){
  60.         if(vis[i] != 1){
  61.             bfs(i);
  62.             cnt++;
  63.             ans.push_back(i);
  64.         }
  65.     }
  66.  
  67.     cout << cnt-1 << endl;
  68.  
  69.     for(int i = 0; i < ans.size(); i++){
  70.         if((i == 0)){
  71.             cout << ans[i] << ' ';
  72.         }
  73.         else if(i == ans.size()-1){
  74.             cout << ans[i] << endl;
  75.         }
  76.         else{
  77.             cout << ans[i] << endl;
  78.             cout << ans[i] << ' ';
  79.         }
  80.     }
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement