Cod sursa(job #3374373)

Utilizator CondoracheTudorCondorache Tudor CondoracheTudor Data 8 noiembrie 2026 23:31:56
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

vector<int> adj[100005];
int idx[100005], low[100005];
bool in_st[100005];
vector<int> st;
vector<vector<int>> ctc;
int timer;

void dfs(int u) {
    idx[u] = low[u] = ++timer;
    st.push_back(u);
    in_st[u] = true;

    for (int v : adj[u]) {
        if (!idx[v]) {
            dfs(v);
            low[u] = min(low[u], low[v]);
        } else if (in_st[v]) {
            low[u] = min(low[u], idx[v]);
        }
    }

    if (low[u] == idx[u]) {
        vector<int> comp;
        while (true) {
            int v = st.back();
            st.pop_back();
            in_st[v] = false;
            comp.push_back(v);
            if (u == v) break;
        }
        ctc.push_back(comp);
    }
}

int main() {
    ifstream fin("ctc.in");
    ofstream fout("ctc.out");

    int n, m;
    fin >> n >> m;

    for (int i = 0; i < m; ++i) {
        int u, v;
        fin >> u >> v;
        adj[u].push_back(v);
    }

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

    fout << ctc.size() << "\n";
    for (const auto& comp : ctc) {
        for (int node : comp) {
            fout << node << " ";
        }
        fout << "\n";
    }

    return 0;
}