Cod sursa(job #3373787)

Utilizator indianu_talpa_iuteTisca Catalin indianu_talpa_iute Data 7 noiembrie 2026 21:39:55
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <vector>

std::ifstream fin("ctc.in");
std::ofstream fout("ctc.out");

const int NMAX = 100005;

int n, m;
std::vector<int> graph[NMAX];
std::vector<int> reversed[NMAX];

bool visited[NMAX];
int pos[NMAX];
int path[NMAX], depth = 0;
int finished[NMAX], cnt = 0;

int comp[NMAX], comps = 0;
int stk[NMAX], top = 0;
std::vector<std::vector<int>> components;

void dfs(int start) {
    visited[start] = true;
    path[depth++] = start;

    while (depth > 0) {
        int node = path[depth - 1];

        if (pos[node] == graph[node].size()) {
            finished[cnt++] = node;
            depth--;
            continue;
        }

        int next = graph[node][pos[node]++];
        if (!visited[next]) {
            visited[next] = true;
            path[depth++] = next;
        }
    }
}

void assign(int start) {
    std::vector<int> component;
    comp[start] = comps;
    stk[top++] = start;

    while (top > 0) {
        int node = stk[--top];
        component.push_back(node);

        for (int next : reversed[node]) {
            if (comp[next] == -1) {
                comp[next] = comps;
                stk[top++] = next;
            }
        }
    }

    components.push_back(component);
    comps++;
}

int main() {
    fin >> n >> m;

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

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

    for (int i = 1; i <= n; i++)
        comp[i] = -1;

    for (int i = cnt - 1; i >= 0; i--)
        if (comp[finished[i]] == -1)
            assign(finished[i]);

    fout << comps << '\n';
    for (auto &component : components) {
        for (int x : component)
            fout << x << ' ';
        fout << '\n';
    }

    return 0;
}