DuongNhi99

CONNECT (lqdoj) - SoLienThong

Mar 26th, 2021 (edited)
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 1e5 + 5;
  5.  
  6. int n, nE;
  7. vector<int> graph[N];
  8.  
  9. int visited[N];
  10. vector<int> comp[N];
  11.  
  12. void DFS(int u, int id) {
  13.     visited[u] = true;
  14.     comp[id].push_back(u);
  15.  
  16.     for (int v: graph[u]) {
  17.         if (!visited[v]) {
  18.             DFS(v, id);
  19.         }
  20.     }
  21. }
  22.  
  23. int main() {
  24. #ifdef LOCAL
  25.     freopen("in.txt", "r", stdin);
  26. #else
  27.     freopen("CONNECT.inp", "r", stdin);
  28.     freopen("CONNECT.out", "w", stdout);
  29. #endif // LOCAL
  30.     ios_base::sync_with_stdio(false);
  31.     cin.tie(NULL);
  32.  
  33.     cin >> n >> nE;
  34.     for (int i = 1; i <= nE; ++i) {
  35.         int u, v; cin >> u >> v;
  36.         graph[u].push_back(v);
  37.         graph[v].push_back(u);
  38.     }
  39.  
  40.     int id = 0;
  41.     int ans = 0;
  42.     for (int i = 1; i <= n; ++i) {
  43.         if (!visited[i]) {
  44.             DFS(i, ++id);
  45.             ans++;
  46.         }
  47.     }
  48.  
  49.     cout << ans << '\n';
  50.     for (int i = 1; i <= ans; ++i) {
  51.         cout << comp[i].size() << ' ';
  52.         for (int u: comp[i])
  53.             cout << u << ' ';
  54.         cout <<'\n';
  55.     }
  56.  
  57.     return 0;
  58. }
  59. // https://lqdoj.edu.vn/problem/connect
Add Comment
Please, Sign In to add comment