Cod sursa(job #2869951)

Utilizator Sebi_MafteiMaftei Sebastioan Sebi_Maftei Data 11 martie 2022 22:40:27
Problema Componente tare conexe Scor 100
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, st[100003], len, elc;
vector<int> ctc[100003];
vector<int> h[100003];
vector<int> g[100003];
bitset<100003> viz;

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

void DFS(int k)
{
    viz[k] = 1;
    for (int w : h[k])
        if (viz[w] == 0)
            DFS(w);
    st[++len] = k;
}

void SortTop()
{
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0) DFS(i);
}

void DFS_inv(int k)
{
    viz[k] = 0;
    ctc[elc].push_back(k);
    for (int w : g[k])
        if (viz[w] == 1)
            DFS_inv(w);
}

void CTC()
{
    for (int i = len; i >= 1; i--)
        if (viz[st[i]] == 1)
        {
            elc++;
            DFS_inv(st[i]);
        }
    fout << elc << "\n";
    for (int i = 1; i <= elc; i++)
    {
        for (int w : ctc[i]) fout << w << " ";
        fout << "\n";
    }
}

int main()
{
    Citire();
    SortTop();
    CTC();
    return 0;
}