Cod sursa(job #3166643)

Utilizator donCiuarinArin Donciu donCiuarin Data 9 noiembrie 2023 10:22:49
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
#define pb push_back
#define NM 100005

using namespace std;

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

int n, m;
int x, y;
bool vz[NM];
int nrct;
vector <int> g[NM], gt[NM];
vector <int> z, ctc[NM];

void vzToZero()
{
    int i;
    for(i = 1; i <= n; i++)
        vz[i] = false;
}

void dfs(int nod)
{
    vz[nod] = true;
    for(int w : g[nod])
        if(!vz[w])
            dfs(w);
    z.pb(nod);
}

void dfst(int nod)
{
    ctc[nrct].pb(nod);
    vz[nod] = true;
    for(int w : gt[nod])
        if(!vz[w])
            dfst(w);
}

int main()
{
    int i, j;
    fin >> n >> m;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        g[x].pb(y);
        gt[y].pb(x);
    }

    for(i = 1; i <= n; i++)
        if(!vz[i])
            dfs(i);

    vzToZero();

    for(i = z.size() - 1; i >= 0; i--)
        if(!vz[z[i]])
        {
            nrct++;
            dfst(z[i]);
        }

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

    return 0;
}