Cod sursa(job #2964506)

Utilizator PalcPalcu Stefan Palc Data 13 ianuarie 2023 09:28:25
Problema Componente tare conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
int st[100005], top, k;
vector<int> a[100005], b[100005], sol[100005];
bitset<100005> viz;

void DFS1(int x)
{
    viz[x] = 1;
    for (auto e : a[x])
        if (viz[e] == 0)
            DFS1(e);
    st[++top] = x;
}

void DFS2(int x)
{
    viz[x] = 1;
    sol[k].push_back(x);
    for (auto e : b[x])
        if (viz[e] == 0)
            DFS2(e);
}

int main()
{
    int x, y;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        a[x].push_back(y);
        b[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0) DFS1(i);
    viz.reset();
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0)
        {
            k++;
            DFS2(i);
        }
    fout << k << "\n";
    for (int i = 1; i <= k; i++)
    {
        sort(sol[i].begin(), sol[i].end());
        for (auto e : sol[i])
            fout << e << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}