Cod sursa(job #2530671)

Utilizator ikogamesIon Ceaun ikogames Data 25 ianuarie 2020 09:04:50
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#define nmax 100003
using namespace std;

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

vector <int> L[nmax];
vector <int> H[nmax];
bool viz[nmax];
vector <int> ctc[nmax];
int n, m, nrc;
int v[nmax], k;
void Read()
{
    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);
    }
    fin.close();
}

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] == true) DFS2(i);
    ctc[nrc].push_back(nod);
}

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

void Print()
{
    fout << nrc << "\n";
    for (int i = 1; i <= nrc; i++)
    {
        for (auto j : ctc[i])
            fout << j << " ";
        fout << "\n";
    }
    fout.close();
}
int main()
{
    Read();
    Kosaraju();
    Print();
    return 0;
}