Cod sursa(job #3358014)

Utilizator TestLicenta123Test Test TestLicenta123 Data 13 iunie 2026 22:58:08
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

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

vector<vector<int>> g, gt;
vector<bool> viz;
vector<int> comp;
vector<vector<int>> comps;
stack<int> st;
int n, m;

void dfs1(int nod) {
    viz[nod] = true;
    for (int vec : g[nod])
        if (!viz[vec])
            dfs1(vec);
    st.push(nod);
}

void dfs2(int nod) {
    viz[nod] = true;
    comp.push_back(nod);
    for (int vec : gt[nod])
        if (!viz[vec])
            dfs2(vec);
}

int main() {
    fin >> n >> m;
    g.resize(n + 1);
    gt.resize(n + 1);
    for (int i = 0; i < m; ++i) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }

    viz.assign(n + 1, false);
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs1(i);

    viz.assign(n + 1, false);
    while (!st.empty()) {
        int nod = st.top();
        st.pop();
        if (!viz[nod]) {
            comp.clear();
            dfs2(nod);
            comps.push_back(comp);
        }
    }

    fout << comps.size() << '\n';
    for (auto& c : comps) {
        for (int nod : c)
            fout << nod << ' ';
        fout << '\n';
    }

    return 0;
}