Cod sursa(job #3240376)

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

int n, m, x, y, ctc[100005], nr;
vector <int> G[100005], GT[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[nod] = nr;
    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 (j = 1 ; j <= n ; j++)
                if (ctc[j] == i)
                    fout << j << " ";
            fout << "\n";
        }
}