Cod sursa(job #3353974)

Utilizator rapidu36Victor Manz rapidu36 Data 13 mai 2026 09:55:39
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

void dfs_s(int x, vector <bool> &viz, vector <vector <int>> &l_s, stack <int> &s) {
    viz[x] = true;
    for (auto y: l_s[x]) {
        if (!viz[y]) {
            dfs_s(y, viz, l_s, s);
        }
    }
    s.push(x);
}

void dfs_p(int x, vector <bool> &viz, vector <vector <int>> &l_p, vector <int> &ctc) {
    viz[x] = true;
    ctc.push_back(x);
    for (auto y: l_p[x]) {
        if (!viz[y]) {
            dfs_p(y, viz, l_p, ctc);
        }
    }
}

int main() {
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int n, m;
    in >> n >> m;
    vector <vector <int>> l_s(n + 1);
    vector <vector <int>> l_p(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y;
        in >> x >> y;
        l_s[x].push_back(y);
        l_p[y].push_back(x); // pentru graful transpus
    }
    in.close();
    // prima etapa: pseudosortarea topologica
    stack <int> s;
    vector <bool> viz(n + 1, false);
    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            dfs_s(i, viz, l_s, s);
        }
    }
    // a doua etapa: obtinerea ctc pe baza stivei
    vector <vector <int>> ctc;
    fill(viz.begin(), viz.end(), false);
    while (!s.empty()) {
        int x = s.top();
        s.pop();
        if (!viz[x]) {
            vector <int> ctc_c;
            dfs_p(x, viz, l_p, ctc_c);
            ctc.push_back(ctc_c);
        }
    }
    out << ctc.size() << "\n";
    for (auto c: ctc) {
        for (auto x: c) {
            out << x << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}