Cod sursa(job #2198313)

Utilizator andreigeorge08Sandu Ciorba andreigeorge08 Data 24 aprilie 2018 10:48:58
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

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

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

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);
    }
}

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[cc].push_back(nod);
}

int main()
{
    Citire();
    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]])
        {
            ++cc;
            L[cc].clear();
            DFS2(sir[i]);
        }

    fout << cc << "\n";
    for(int i = 1; i <= cc; i++)
    {
        for(int j = 0; j < L[i].size(); j++)
            fout << L[i][j] << " ";
        fout << "\n";
    }
    return 0;
}