Cod sursa(job #2865931)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 9 martie 2022 11:37:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

int n,m;
vector < int > v[100005];
vector < int > vt[100005];
vector < int > ctc[100005];
int nr_ctc,x,y;
stack < int > st;
bool viz[100005];

void dfs(int nod) {
    viz[nod]=1;
    for (auto k:v[nod]) {
        if (!viz[k]) dfs(k);
    }
    st.push(nod);
}

void dfs_t(int nod) {
    viz[nod]=0;
    for (auto k:vt[nod]) {
        if (viz[k]) dfs_t(k);
    }
    ctc[nr_ctc].push_back(nod);
}

void kosaraju() {
    for (int i=1;i<=n;i++) {
        if (!viz[i]) dfs(i);
    }
    while (!st.empty()) {
        int nod = st.top();
        if (viz[nod]) {
            nr_ctc++;
            dfs_t(nod);
        }
        st.pop();
    }
}

void read() {
    f >> n >> m;
    for (int i=1;i<=m;i++) {
        f >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
}

void show() {
    g << nr_ctc << '\n';
    for (int i=1;i<=nr_ctc;i++) {
        for (auto k:ctc[i]) g << k << " ";
        g << '\n';
    }
}

int main()
{
    read();
    kosaraju();
    show();
    return 0;
}