Cod sursa(job #2808083)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 24 noiembrie 2021 16:08:26
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;

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

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

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

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

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

void kosaraju() {
    while (st.empty()==0) {
        int nod = st.top();
        if (viz[nod]==1) {
            nr_ctc++;
            dfs_t(nod);
        }
        st.pop();
    }
}

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_graph();
    for (int i=1;i<=n;i++) {
        if (viz[i]==0) {
            dfs(i);
        }
    }
    kosaraju();
    show();
    return 0;
}