Cod sursa(job #3371288)

Utilizator laurentiu.maticaMatica Laurentiu-Andrei laurentiu.matica Data 29 octombrie 2026 16:54:40
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

ifstream cin("ctc.in");
ofstream cout("ctc.out");

vector<vector<int>> graf;
vector<vector<int>> graft;
vector<vector<int>> scc;
vector<int> viz;
stack<int> s;
int n,m,ctc;

void dfs(const int nod) {
    viz[nod] = 1;

    for (const auto x : graf[nod]) {
        if (!viz[x]) {
            dfs(x);
        }
    }

    s.push(nod);
}

void dfs2(const int nod) {
    viz[nod] = 0;

    for (const auto x: graft[nod]) {
        if (viz[x]) {
            dfs2(x);
        }
    }

    scc[ctc].push_back(nod);
}

int main() {
    cin >> n >> m;
    graf.resize(n+1);
    graft.resize(n+1);
    viz.resize(n+1,0);

    for (int i = 0; i < m; i++) {
        int x,y;
        cin >> x >> y;
        graf[x].push_back(y);
        graft[y].push_back(x);
    }

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

    while (!s.empty()) {
        if (viz[s.top()]) {
            scc.emplace_back();
            dfs2(s.top());
            ctc++;
        }
        s.pop();
    }

    cout << ctc << '\n';
    for (const auto &vec : scc) {
        for (const auto x : vec)
            cout << x << ' ';

        cout << '\n';
    }

    return 0;
}