Cod sursa(job #2886255)

Utilizator Mihnea_DumitruDumitru Mihnea-Andrei Mihnea_Dumitru Data 7 aprilie 2022 14:58:05
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

const int N = 1e5;

vector<int> succesori[N + 1], predecesori[N + 1];
vector<int> ctc[N + 1];
vector<int> s;
bitset<N + 1> viz;
int n, nc;

void dfs(int x) {
    viz[x] = 1;
    for (auto y: succesori[x]) {
        if (!viz[y]) {
            dfs(y);
        }
    }
    s.push_back(x);
}

void dfs_t(int x) {
    ctc[nc].push_back(x);
    viz[x] = 1;
    for (auto y: predecesori[x]) {
        if (!viz[y]) {
            dfs_t(y);
        }
    }
}

int main() {
    int 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);
    }
    in.close();

    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            dfs(i);
        }
    }

    viz.reset();
    for (int i = (int) s.size() - 1; i >= 0; i--) {
        if (!viz[s[i]]) {
            nc++;
            dfs_t(s[i]);
        }
    }

    out << nc << "\n";
    for (int i = 1; i <= nc; i++) {

        for (auto x: ctc[i]) {
            out << x << " ";
        }
        out << "\n";
    }

    out.close();
    return 0;
}