Cod sursa(job #3151702)

Utilizator TeddyDinutaDinuta Eduard Stefan TeddyDinuta Data 22 septembrie 2023 17:13:10
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
int n, m, x, y, c, t;
vector<int> v[100005];
int k = 0, st[100005];
vector<int> comp[100005];
int ap[100005], low[100005], found[100005];

void dfs(int nod) {

    low[nod] = t;
    found[nod] = t;
    ++t;
    st[++k] = nod;
    ap[nod] = 1;

    for (auto it : v[nod]) {
        if (found[it] == 0) {
            dfs(it);
            low[nod] = min(low[nod], low[it]);
        } else if (ap[it] == 1) {
            low[nod] = min(low[nod], found[it]);
        }
    }

    if (low[nod] == found[nod]) {
        c++;
        while (st[k] != nod) {
            comp[c].push_back(st[k]);
            ap[st[k]] = 0;
            k--;
        }

        comp[c].push_back(st[k]);
        ap[st[k]] = 0;
        k--;
    }
}
int main()
{
    in >> n >> m;

    for (int i = 1; i <= m; i++) {
        in >> x >> y;
        v[x].push_back(y);
    }

    for (int i = 1; i <= n; i++) {
        if (found[i] == 0) {
            t = 1;
            k = 0;
            dfs(i);
        }
    }

    out << c << '\n';

    for (int i = 1; i <= c; i++) {

        for (auto it : comp[i])
            out << it << " ";
        out << '\n';
    }
    return 0;
}