Cod sursa(job #3343097)

Utilizator stanrares1002@gmail.comRares Stan [email protected] Data 26 februarie 2026 14:26:18
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define ll long long

const int NMAX = 1e5 + 5;

vector <int> g1[NMAX];
vector <int> g2[NMAX];

stack <int> s;

bool viz[NMAX];

void DFS (int node) {
    viz[node] = true;
    for (int x: g1[node])
        if (!viz[x])
            DFS(x);
    s.push(node);
}

vector <int> sol[NMAX];

void DFS2 (int node, const int p) {
    viz[node] = true;
    for (int x: g2[node]) {
        if (!viz[x]) {
            sol[p].pb(x);
            DFS2(x, p);
        }
    }
}

int main() {
    ifstream cin("ctc.in");
    ofstream cout("ctc.out");
    ios::sync_with_stdio(false), cin.tie(0);
    int n, m;
    cin >> n >> m;
    for (int i = 1,x ,y; i <= m; i++) {
        cin >> x >> y;
        g1[x].pb(y);
        g2[y].pb(x);
    }
    for (int i = 1; i <= n; i++) {
        if (!viz[i]) DFS(i);
    }

    for (int i = 1; i <= n; i++) viz[i] = false;

    int p = 0;
    while (!s.empty()) {
        int u = s.top();
        s.pop();
        if (viz[u]) continue;
        p++;
        sol[p].pb(u);
        DFS2(u, p);

    }
    cout << p << '\n';
    for (int i = 1; i <= p; i++) {
        for (int x: sol[i]) cout << x << " ";
        cout << '\n';
    }
    return 0;
}