Cod sursa(job #2842711)

Utilizator mirunaaCociorva Miruna mirunaa Data 1 februarie 2022 13:25:50
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
#define NMAX 100004

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

int n, m, poz;
///GT -> graful G transpus
vector <int> G[NMAX], GT[NMAX];
bool viz[NMAX];
int nr;///nr comp tare conexe
vector <int> ctc[NMAX];
int postordine[NMAX];

void citire();
void afisare();
void DFS(int x);
void DFST(int x);
void afisare();

int main()
{
    citire();
    ///parcurg DFS graful G retinand vf in postordine
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            DFS(i);
    ///parcurg vectorul postordine de la dreapta la stanga si fac DFST in graful transpus
    for (int i = n; i > 0; i--)
        if (viz[postordine[i]])
        {
            nr++;
            DFST(postordine[i]);
        }
    afisare();
    return 0;
}

void citire()
{
    int x, y;
    fin >> n >> m;
    for (int i = 1; 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 vecin = 0; vecin < G[x].size(); vecin++)
        if (!viz[G[x][vecin]])
            DFS(G[x][vecin]);
    postordine[++poz] = x;
}

void DFST(int x)
{
    viz[x] = 0;
    ///retin nodul in comp conexa
    ctc[nr].push_back(x);
    for (int vecin = 0; vecin < GT[x].size(); vecin++)
        if (viz[GT[x][vecin]])
            DFST(GT[x][vecin]);
}

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