Cod sursa(job #1922773)

Utilizator razvan99hHorhat Razvan razvan99h Data 10 martie 2017 18:51:37
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <fstream>
#include <vector>
#define DM 100005
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n, m, a, b, top, st[DM], nrc;
bool viz[DM], vizt[DM];
vector <int> g[DM], gt[DM], ctc[DM];

void dfs(int nod)
{
    viz[nod] = 1;
    for(auto it : g[nod])
        if(!viz[it])
            dfs(it);
    st[++top] = nod;
}

void dfst(int nod)
{
    vizt[nod] = 1;
    ctc[nrc].push_back(nod);
    for(auto it : gt[nod])
        if(!vizt[it])
            dfst(it);
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> a >> b;
        g[a].push_back(b);
        gt[b].push_back(a);
    }

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

    for(int i = n; i >= 1; i--)
        if(!vizt[st[i]])
        {
            nrc++;
            dfst(st[i]);
        }

    fout << nrc << '\n';
    for(int i = 1; i <= nrc; i++)
    {
        for(auto it : ctc[i])
            fout << it << ' ';
        fout<<'\n';
    }
    return 0;
}