Cod sursa(job #3374636)

Utilizator suchea.silviuSuchea Silvius suchea.silviu Data 9 noiembrie 2026 08:13:51
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n, m;
vector<int> g[100001], gt[100001], ordine, comp[100001];
bool viz[100001];
int nrc;

void dfs1(int u) {
    viz[u] = true;
    for (int v : g[u])
        if (!viz[v]) dfs1(v);
    ordine.push_back(u);
}

void dfs2(int u) {
    viz[u] = false;
    comp[nrc].push_back(u);
    for (int v : gt[u])
        if (viz[v]) dfs2(v);
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (!viz[i]) dfs1(i);
    for (int i = n - 1; i >= 0; i--)
        if (viz[ordine[i]]) {
            nrc++;
            dfs2(ordine[i]);
        }
    fout << nrc << "\n";
    for (int c = 1; c <= nrc; c++) {
        for (int x : comp[c]) fout << x << " ";
        fout << "\n";
    }
    return 0;
}