Cod sursa(job #3357040)

Utilizator cont_superscoalaSuperScoala cont_superscoala Data 5 iunie 2026 11:24:14
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
/*
https://infoarena.ro/problema/ctc
*/
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

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

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);
    }
    in.close();
    /// etapa 1: construim stiva ("sortare topologica")
    vector <bool> viz(n + 1, false);
    stack <int> stiva;
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs_s(i, l_s, viz, stiva);
        }
    }
    /// etapa 2: construim listele ctc-urilor
    fill(viz.begin(), viz.end(), false);
    vector <vector <int>> ctc;
    while (!stiva.empty())
    {
        int x = stiva.top();
        stiva.pop();
        if (!viz[x])
        {
            vector <int> ctc_c;
            dfs_p(x, l_p, viz, 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;
}