Cod sursa(job #3294953)

Utilizator rapidu36Victor Manz rapidu36 Data 30 aprilie 2025 17:48:04
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

vector <vector <int>> su, pr;
vector <vector <int>> ctc;
vector <bool> viz;
vector <int> ps_sort;

void dfs_su(int x)
{
    viz[x] = true;
    for (auto y: su[x])
    {
        if (!viz[y])
        {
            dfs_su(y);
        }
    }
    ps_sort.push_back(x);
}

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

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");
    int n, m;
    in >> n >> m;
    su.resize(n + 1);
    pr.resize(n + 1);
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        su[x].push_back(y);
        pr[y].push_back(x);
    }
    viz.resize(n + 1, false);
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs_su(i);
        }
    }
    fill(viz.begin(), viz.end(), false);
    reverse(ps_sort.begin(), ps_sort.end());
    for (auto x: ps_sort)
    {
        if (!viz[x])
        {
            vector <int> comp;
            dfs_pr(x, comp);
            ctc.push_back(comp);
        }
    }
    out << ctc.size() << "\n";
    for (auto c: ctc)
    {
        for (auto x: c)
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}