Cod sursa(job #3370771)

Utilizator MihaiDBRDobrin Mihai MihaiDBR Data 27 octombrie 2026 11:17:53
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n, m, nrc;
vector<int> v[100005], vt[100005], comp[100005];
bool vizitat[100005];
stack<int> st;

void dfs1(int x) {
    vizitat[x] = true;
    for (int y : v[x])
        if (!vizitat[y])
            dfs1(y);
    st.push(x);
}

void dfs2(int x) {
    vizitat[x] = true;
    comp[nrc].push_back(x);
    for (int y : vt[x])
        if (!vizitat[y])
            dfs2(y);
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (!vizitat[i])
            dfs1(i);
    for (int i = 1; i <= n; i++)
        vizitat[i] = false;
    while (!st.empty()) {
        int x = st.top();
        st.pop();
        if (!vizitat[x]) {
            nrc++;
            dfs2(x);
        }
    }
    fout << nrc << '\n';
    for (int i = 1; i <= nrc; i++) {
        for (int x : comp[i])
            fout << x << ' ';
        fout << '\n';
    }
    return 0;
}