Cod sursa(job #2173356)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 15 martie 2018 21:49:32
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
#define nmax 100005
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

vector <int> L[nmax];
vector <int> G[nmax];
int sir[nmax], n, m, k, c;
bool viz[nmax];

void DFS(int nod)
{
    viz[nod] = 1;

    for(auto i : L[nod])
        if(!viz[i])
            DFS(i);
    sir[++k] = nod;
}

void DFS2(int nod)
{
    viz[nod] = 1;

    for(auto i : G[nod])
        if(!viz[i])
            DFS2(i);
    L[c].push_back(nod);
}

void Citire()
{
    int x, y;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        G[y].push_back(x);
    }

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

    for(int i = 1; i <= n; i++) viz[i] = 0;

    for(int i = k; i >= 1; i--)
        if(!viz[sir[i]])
        {
            ++c;
            L[c].clear();
            DFS2(sir[i]);
        }

    fout << c << "\n";
    for(int i = 1; i <= c; i++){
        for(auto j : L[i])
            fout << j << " ";
        fout << "\n";
    }
}
int main()
{
    Citire();
    return 0;
}