Cod sursa(job #2974469)

Utilizator Iordache_CezarIordache Cezar Iordache_Cezar Data 4 februarie 2023 09:44:09
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define NMAX 100008

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

int n, m, cnt, lg;
bool viz[NMAX];

int postordine[NMAX];
vector <int> G[NMAX], GT[NMAX], ctc[NMAX];

void DFS(int nod);
void DFST(int nod);

int main()
{
    ios_base::sync_with_stdio(0); fin.tie(0);
    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);
    }
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0)
            DFS(i);
    for (int i = n-1; i >= 0; i--)
        if (viz[postordine[i]] == 1)
        {
            cnt++;
            DFST(postordine[i]);
        }
    fout << cnt << '\n';
    for (int i = 1; i <= cnt; i++)
    {
        for (auto el : ctc[i])
            fout << el << ' ';
        fout << '\n';
    }
    return 0;
}

void DFS(int nod)
{
    viz[nod] = 1;
    for (auto el : G[nod])
        if (viz[el] == 0)
            DFS(el);
    postordine[lg++] = nod;
}

void DFST(int nod)
{
    viz[nod] = 0;
    ctc[cnt].push_back(nod);
    for (auto el : GT[nod])
        if (viz[el] == 1)
            DFST(el);
}