Cod sursa(job #3232638)

Utilizator drsbosDarius Scripcaru drsbos Data 31 mai 2024 17:53:23
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>
#include <stack>

using namespace std;

const int N = 1e5 + 1;

vector <int> L[N], T[N];
int n, m;
bitset <N> viz;
stack <int> st;
vector < vector <int> > ctc;

void Read()
{
    ifstream fin("ctc.in");
    fin >> n >> m;
    while (m--)
    {
        int x, y;
        fin >> x >> y;
        L[x].push_back(y);
        T[y].push_back(x);
    }
}

void DFS1(int nod)
{
    viz[nod] = 1;
    for (auto next : L[nod])
        if (!viz[next])
            DFS1(next);
    st.push(nod);
}

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

void Kosaraju()
{
    for (int i = 1; i <= n; i++)
        if (!viz[i])
            DFS1(i);
    viz.reset();
    while (!st.empty()) {
        int curr = st.top();
        st.pop();
        if (!viz[curr]) {
            ctc.push_back({});
            DFS2(curr);
        }
    }
    ofstream fout("ctc.in");
    fout << ctc.size() << '\n';
    for (auto& comp : ctc)
    {
        for (auto& it : comp)
            fout << it << " ";
        fout << '\n';
    }
}

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