Cod sursa(job #3357717)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 13:05:06
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>

std::vector<std::vector<int>> graph;
std::vector<std::vector<int>> transpose;
std::vector<int> stack;
std::vector<bool> visited;
std::vector<int> roots;

void dfs1(int node) {
    visited[node] = true;
    for (const auto &x: graph[node]) {
        if (!visited[x]) {
            dfs1(x);
        }
    }
    stack.push_back(node);
}

void dfs2(int node, int root) {
    roots[node] = root;
    for (const auto &x: transpose[node]) {
        if (roots[x] == 0) {
            dfs2(x, root);
        }
    }
}

int main() {
    std::ifstream input("ctc.in");
    std::ofstream output("ctc.out");

    int n, m;
    input >> n >> m;

    graph.resize(n + 1);
    transpose.resize(n + 1);
    visited.assign(n + 1, false);
    roots.assign(n + 1, 0);

    for (int i = 0; i < m; ++i) {
        int x, y;
        input >> x >> y;
        graph[x].push_back(y);
        transpose[y].push_back(x);
    }

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

    std::vector<std::vector<int>> components;
    std::vector<int> comp;

    while (!stack.empty()) {
        int node = stack.back();
        stack.pop_back();
        if (roots[node] == 0) {
            comp.clear();
            dfs2(node, node);
            for (int i = 1; i <= n; ++i) {
                if (roots[i] == node) {
                    comp.push_back(i);
                }
            }
            components.push_back(comp);
        }
    }

    output << components.size() << '\n';
    for (const auto& component : components) {
        for (const auto& node : component) {
            output << node << " ";
        }
        output << '\n';
    }

    return 0;
}