Cod sursa(job #3240378)

Utilizator CimpoesuFabianCimpoesu Fabian George CimpoesuFabian Data 14 august 2024 15:46:50
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n, m, x, y, nr;
vector <int> G[100005], GT[100005], ctc[100005];
stack <int> q;
bitset <100005> viz;

void dfs1(int nod)
{
    viz[nod] = 1;
    for (auto next : G[nod])
        if (viz[next] == 0)
            dfs1(next);
    q.push(nod);
}

void dfs2(int nod)
{
    viz[nod] = 1;
    ctc[nr].push_back(nod);
    for (auto next : GT[nod])
        if (viz[next] == 0)
            dfs2(next);
}

int main()
{
    int i, j, nod;
    fin >> n >> m;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    for (i = 1 ; i <= n ; i++)
        if (viz[i] == 0)
            dfs1(i);
    viz.reset();
    while (!q.empty())
    {
        nod = q.top();
        q.pop();
        if (viz[nod] == 0)
        {
            ++nr;
            dfs2(nod);
        }
    }
    fout << nr << "\n";
    for (i = 1 ; i <= nr ; i++)
    {
        for (auto next : ctc[i])
            fout << next << " ";
        fout << "\n";
    }
}