Cod sursa(job #3270176)

Utilizator Chiratcu_RaresChiratcu Rares-Andrei Chiratcu_Rares Data 22 ianuarie 2025 12:45:59
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <vector>
#define NMAX 100002

using namespace std;

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

int n, nr, nrc;
vector <int> G[NMAX];
vector <int> GT[NMAX];
int post[NMAX];
bool viz [NMAX];
vector <int> ctc[NMAX];
void citire();
void DFS(int x);
void DFST(int x);
void afisare ();

int main()
{
    citire();
    for (int i=1; i<=n; i++)
        if (!viz[i])
            DFS(i);
    for (int i=n; i>0; i--)
        if (viz[post[i]])
            {
                nrc++;
                DFST(post[i]);

            }
    afisare();
    return 0;
}

void citire()
{
    int m, 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 DFS(int x)
{
    viz[x]=1;
    for (int i=0; i<G[x].size(); i++)
        if (!viz[G[x][i]])
            DFS (G[x][i]);
    post[++nr]=x;
}
void DFST(int x)
{
    viz[x]=0;
    ctc[nrc].push_back(x);
    for (int i=0; i<GT[x].size(); i++)
        if (viz[GT[x][i]])
            DFST (GT[x][i]);
}
void afisare ()
{
    fout << nrc << '\n';
    for (int i=1; i<=nrc; i++)
    {
        for (int j=0; j<ctc[i].size(); j++)
            fout << ctc[i][j] << ' ';
        fout<<'\n';
    }
}