Cod sursa(job #3040422)

Utilizator SergetecLefter Sergiu Sergetec Data 29 martie 2023 21:06:20
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
/*
 * Lefter Sergiu - 29/03/2023
*/
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int N = 1e5;

int c[N+1];
bool viz[N+1];
stack<int> stiva;
vector<int> succesori[N+1], predecesori[N+1], ctc[N+1];

void dfs_ini(int x) {
    viz[x] = true;
    for (auto y: succesori[x]) {
        if (!viz[y]) {
            dfs_ini(y);
        }
    }
    stiva.push(x);
}

void dfs_trans(int x, int nc) {
    c[x] = nc;
    for (auto y: predecesori[x]) {
        if (c[y] == 0) {
            dfs_trans(y, nc);
        }
    }
}

int main() {
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; ++i) {
        int x, y;
        in >> x >> y;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i) {
        if (!viz[i]) {
            dfs_ini(i);
        }
    }
    int nc = 0;
    while (!stiva.empty()) {
        int x = stiva.top();
        stiva.pop();
        if (c[x] == 0) {
            dfs_trans(x, ++nc);
        }
    }
    for (int i = 1; i <= n; ++i) {
        ctc[c[i]].push_back(i);
    }
    out << nc << "\n";
    for (int i = 1; i <= nc; ++i) {
        for (auto x: ctc[i]) {
            out << x << " ";
        }
        out << '\n';
    }
    in.close();
    out.close();
    return 0;
}