Cod sursa(job #3344919)

Utilizator rapidu36Victor Manz rapidu36 Data 6 martie 2026 17:38:59
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

const int N = 1e5;

vector <int> ls[N+1], lp[N+1], ctc[N+1];
bool viz[N+1];
stack <int> stiva;

void dfs_s(int x)
{
    viz[x] = true;
    for (auto y: ls[x])
    {
        if (!viz[y])
        {
            dfs_s(y);
        }
    }
    stiva.push(x);
}

void dfs_p(int x, int nctc)
{
    ctc[nctc].push_back(x);
    viz[x] = true;
    for (auto y: lp[x])
    {
        if (!viz[y])
        {
            dfs_p(y, nctc);
        }
    }

}

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int n, m;
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        ls[x].push_back(y);
        lp[y].push_back(x);
    }
    in.close();
    ///etapa 1 (pseudo sortare topologica)
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs_s(i);
        }
    }
    ///etapa 2: parcurgere a stivei si dfs pe graful transpus
    for (int i = 1; i <= n; i++)
    {
        viz[i] = false;
    }
    int nr_ctc = 0;
    while (!stiva.empty())
    {
        int x = stiva.top();
        stiva.pop();
        if (!viz[x])
        {
            nr_ctc++;
            dfs_p(x, nr_ctc);
        }
    }
    out << nr_ctc << "\n";
    for (int i = 1; i <= nr_ctc; i++)
    {
        ///afisam varfurile din ctc cu numarul i
        for (auto x: ctc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}