Cod sursa(job #3351412)

Utilizator eric_dragosDragos Eric eric_dragos Data 18 aprilie 2026 22:18:54
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n,m;
vector<vector<int>> adj, revAdj;
void citire(){
    fin >> n >> m;
    adj.resize(n+1);
    revAdj.resize(n+1);
    int x,y;
    while(m--){
        fin >> x >> y;
        adj[x].push_back(y);
        revAdj[y].push_back(x);
    }
}
void dfs1(int nod, vector<bool> &viz, stack<int>& st){
    viz[nod] = 1;
    for(int v : adj[nod]){
        if(!viz[v]) dfs1(v, viz, st);
    }
    st.push(nod);
}
void dfs2(int nod, vector<bool>& viz, vector<int> &scc){
    viz[nod] = 1;
    scc.push_back(nod);
    for(int v : revAdj[nod]){
        if(!viz[v]) dfs2(v, viz, scc);
    }
}
vector<vector<int>> kosaraju(){
    vector<vector<int>> total_scc;
    vector<bool> viz(n+1, false);
    stack<int> st;
    for(int i = 1; i<=n; i++){
        if(!viz[i])dfs1(i, viz, st);
    }
    viz.assign(n+1, false);
    while(!st.empty()){
        int u = st.top();
        st.pop();
        if(!viz[u]){
            vector<int> scc;
            dfs2(u, viz, scc);
            total_scc.push_back(scc);
        }
    }

    return total_scc;
}
int main(){
    citire();
    vector<vector<int>> scc = kosaraju();
    fout << scc.size() << '\n';
    for(int i = 0; i<scc.size(); i++){
        for(int j = 0; j< scc[i].size(); j++){
            fout << scc[i][j] << ' ';
        }
        fout << '\n';
    }

    return 0;
}