Cod sursa(job #3342758)

Utilizator radeuojArghira Radu Stefan radeuoj Data 25 februarie 2026 17:03:07
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <iostream>
#include <vector>
#include <stack>

const int MAX_N = 1e5;

struct Node {
    std::vector<int> adj;
    int time_in;
    int low;
    bool on_stack;
};

int n, m;
Node a[MAX_N + 1];
std::vector<std::vector<int>> comps;
std::stack<int> s;

void read_graph() {
    for (int i = 1; i <= m; i++) {
        int u, v;
        std::cin >> u >> v;
        a[u].adj.push_back(v);
    }
}

std::vector<int> pop_comp(int low) {
    std::vector<int> comp;

    while (s.top() != low) {
        comp.push_back(s.top());
        a[s.top()].on_stack = false;
        s.pop();
    }

    comp.push_back(low);
    a[low].on_stack = false;
    s.pop();
    return comp;
}

void dfs(int node) {
    static int time = 0;
    a[node].time_in = a[node].low = ++time;
    a[node].on_stack = true;
    s.push(node);

    for (int child : a[node].adj) {
        if (a[child].time_in == 0) {
            dfs(child);
            a[node].low = std::min(a[node].low, a[child].low);
        } else if (a[child].on_stack) {
            a[node].low = std::min(a[node].low, a[child].time_in);
        }
    }

    if (a[node].low == a[node].time_in) {
        comps.push_back(pop_comp(node));
    }
}

void tarjan() {
    for (int i = 1; i <= n; i++) {
        if (a[i].time_in == 0) {
            dfs(i);
        }
    }
}

void print_comps() {
    std::cout << comps.size() << '\n';

    for (auto comp : comps) {
        for (int node : comp) {
            std::cout << node << ' ';
        }
        std::cout << '\n';
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);

    std::cin >> n >> m;
    read_graph();
    tarjan();
    print_comps();
}