Cod sursa(job #2530676)

Utilizator DragosSDragos Sarbu DragosS Data 25 ianuarie 2020 09:10:31
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
#define nmax 100003

using namespace std;

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

bool viz[nmax];
vector<int> ctc[nmax];
vector<int> L[nmax],H[nmax];
int n,m,nrc;
int v[nmax],k;

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

void DFS1(int nod)
{
    viz[nod] = true;
    for(auto i : L[nod])
        if(!viz[i]) DFS1(i);
    v[++k] = nod;
}

void DFS2(int nod)
{
    viz[nod] = false;
    for(auto i : H[nod])
        if(viz[i]) DFS2(i);
    ctc[nrc].push_back(nod);
}

void Kosaraju()
{
    for(int i = 1; i <= n; i++)
        if(!viz[i])
            DFS1(i);
    for(int i = n; i >= 1; i--)
        if(viz[v[i]])
        {
            nrc++;
            DFS2(v[i]);
        }
}

void Afisare()
{
    fout << nrc << "\n";
    for(int i = 1; i <= nrc; i++)
    {
        for(auto j : ctc[i])
            fout << j << " ";
        fout << "\n";
    }
}

int main()
{
    Citire();
    Kosaraju();
    Afisare();
    fin.close();
    fout.close();
    return 0;
}