Cod sursa(job #3372448)

Utilizator iLaurianLaurian Iacob iLaurian Data 3 noiembrie 2026 22:23:43
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>

std::ifstream f ("ctc.in");
std::ofstream g ("ctc.out");

const int MAXN = 100005;
std::vector<int> adj[MAXN], adj_t[MAXN];
bool viz[MAXN];
std::vector<int> st;
std::vector<int> current_scc;
std::vector<std::vector<int>> all_sccs;

void dfs(int i) {
    viz[i] = true;
    for (auto x : adj[i]) {
        if (!viz[x]) dfs(x);
    }
    st.push_back(i);
}

void dfsT(int i) {
    viz[i] = true;
    current_scc.push_back(i);
    for (auto x : adj_t[i]) {
        if (!viz[x]) dfsT(x);
    }
}

int main() {
    int n, m;
    f >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y; f >> x >> y;
        adj[x].push_back(y);
        adj_t[y].push_back(x);
    }

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

    std::fill(viz, viz + n + 1, false);

    for (int i = n - 1; i >= 0; i--) {
        int node = st[i];
        if (!viz[node]) {
            current_scc.clear();
            dfsT(node);
            all_sccs.push_back(current_scc);
        }
    }

    g << all_sccs.size() << '\n';
    for (const auto& scc : all_sccs) {
        for (int node : scc) {
            g << node << ' ';
        }
        g << '\n';
    }

    return 0;
}