Cod sursa(job #3040251)

Utilizator 55andreiv55Andrei Voicu 55andreiv55 Data 29 martie 2023 16:51:24
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const int N = 1e5;

vector <int> succesori[N+1], predecesori[N+1], ctc[N+1];
int c[N+1];
bool viz[N+1];
stack <int> stiva;

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

void dfs_trans(int x, int nc)
{
    c[x] = nc;
    for (auto y: predecesori[x])
    {
        if (c[y] == 0)
        {
            dfs_trans(y, nc);
        }
    }
}

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;
        succesori[x].push_back(y);
        predecesori[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
    {
        if (!viz[i])
        {
            dfs_ini(i);
        }
    }
    int nc = 0;
    while (!stiva.empty())
    {
        int x = stiva.top();
        stiva.pop();
        if (c[x] == 0)
        {
            dfs_trans(x, ++nc);
        }
    }
    for (int i = 1; i <= n; i++)
    {
        ctc[c[i]].push_back(i);
    }
    out << nc << "\n";
    for (int i = 1; i <= nc; i++)
    {
        for (auto x: ctc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}