Cod sursa(job #3274368)

Utilizator Dragos20012001Szekely Dragos Dragos20012001 Data 6 februarie 2025 16:03:56
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <unordered_map>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <bitset>

using namespace std;

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

vector <int> G[100005], GT[100005], ctc[100005];
int n, m, nr_ctc;
vector <int> ord;
bitset <100005> viz;

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

void DFS1(int nod)
{
    viz[nod] = 1;
    for (auto next : G[nod])
        if (!viz[next])
            DFS1(next);
    ord.push_back(nod);
}

void DFS2(int nod)
{
    viz[nod] = 1;
    ctc[nr_ctc].push_back(nod);
    for (auto next : GT[nod])
        if (!viz[next])
            DFS2(next);
}

void Kosaraju()
{
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            DFS1(i);
    viz.reset();
    reverse(ord.begin(), ord.end());
    for (auto nod : ord)
        if (!viz[nod])
        {
            nr_ctc++;
            DFS2(nod);
        }
}

void Write()
{
    fout << nr_ctc << "\n";
    for (int i = 1; i <= nr_ctc; i++)
    {
        for (auto nod : ctc[i])
            fout << nod << " ";
        fout << "\n";
    }
}

int main()
{
    Read();
    Kosaraju();
    Write();
    return 0;
}