Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int N = 1e5 + 5;
- int n, nE;
- vector<int> graph[N];
- int visited[N];
- vector<int> comp[N];
- void DFS(int u, int id) {
- visited[u] = true;
- comp[id].push_back(u);
- for (int v: graph[u]) {
- if (!visited[v]) {
- DFS(v, id);
- }
- }
- }
- int main() {
- #ifdef LOCAL
- freopen("in.txt", "r", stdin);
- #else
- freopen("CONNECT.inp", "r", stdin);
- freopen("CONNECT.out", "w", stdout);
- #endif // LOCAL
- ios_base::sync_with_stdio(false);
- cin.tie(NULL);
- cin >> n >> nE;
- for (int i = 1; i <= nE; ++i) {
- int u, v; cin >> u >> v;
- graph[u].push_back(v);
- graph[v].push_back(u);
- }
- int id = 0;
- int ans = 0;
- for (int i = 1; i <= n; ++i) {
- if (!visited[i]) {
- DFS(i, ++id);
- ans++;
- }
- }
- cout << ans << '\n';
- for (int i = 1; i <= ans; ++i) {
- cout << comp[i].size() << ' ';
- for (int u: comp[i])
- cout << u << ' ';
- cout <<'\n';
- }
- return 0;
- }
- // https://lqdoj.edu.vn/problem/connect
Add Comment
Please, Sign In to add comment