Cod sursa(job #3340115)

Utilizator bejanrazvan08bejan razvan bejanrazvan08 Data 12 februarie 2026 09:56:25
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>
using namespace std;

const int NMAX = 100002;

ifstream fin ("ctc.in");
ofstream fout ("ctc.out");

int n, m, nrct, poz;
vector<int> G[NMAX];
vector<int> GT[NMAX];
vector<int> CTC[NMAX];

bool viz[NMAX];
int postordine[NMAX];

void citire();
void afisare();
void dfs(int x);
void dfst(int x);

int main()
{
    citire();
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            dfs(i);

    for (int i = n; i > 0; i--)
        if (viz[postordine[i]])
        {
            nrct++;
            dfst(postordine[i]);
        }

    afisare();
    return 0;
}

void citire()
{
    int x, y;
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}

void afisare()
{
    fout << nrct << '\n';
    for (int i = 1; i <= nrct; i++)
    {
        for (int j = 0; j < CTC[i].size(); j++)
            fout << CTC[i][j] << ' ';
        fout << '\n';
    }
}

void dfs(int x)
{
    viz[x] = 1;
    for (int i = 0; i < G[x].size(); i++)
        if (!viz[G[x][i]])
            dfs(G[x][i]);

    postordine[++poz] = x;
}

void dfst(int x)
{
    viz[x] = 0;
    CTC[nrct].push_back(x);

    for (int i = 0; i < GT[x].size(); i++)
        if (viz[GT[x][i]])
            dfst(GT[x][i]);
}