Cod sursa(job #3187619)

Utilizator not_anduAndu Scheusan not_andu Data 29 decembrie 2023 18:21:32
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
/**
 * Author: Andu Scheusan (not_andu)
 * Created: 29.12.2023 17:59:10
*/

#include <bits/stdc++.h>
#pragma GCC optimize("O3")

using namespace std;

#define INFILE "ctc.in"
#define OUTFILE "ctc.out"

typedef long long ll;

const int N_MAX = 1e5 + 5;

int nodes, edges, nowCtc = 0;
vector<int> adj[N_MAX], ctc[N_MAX], revAdj[N_MAX];
bool used[N_MAX];
stack<int> st;

void dfs(int node){
    used[node] = true;
    for(auto to : adj[node]){
        if(!used[to]) dfs(to);
    }
    st.push(node);
}

void transposeDfs(int node){
    used[node] = false;
    ctc[nowCtc].push_back(node);
    for(auto to : revAdj[node]){
        if(used[to]) transposeDfs(to);
    }
}

void kosaraju(){
    
    for(int node = 1; node <= nodes; ++node){
        if(!used[node]) dfs(node);
    }

    while(!st.empty()){
        if(used[st.top()]){
            ++nowCtc;
            transposeDfs(st.top());
        }
        st.pop();
    }

}

void solve(){

    cin >> nodes >> edges;

    for(int i = 0; i < edges; ++i){

        int node1, node2; cin >> node1 >> node2;

        adj[node1].push_back(node2);
        revAdj[node2].push_back(node1);

    }

    kosaraju();

    cout << nowCtc << '\n';

    for(int i = 1; i <= nowCtc; ++i){
        for(int node : ctc[i]){
            cout << node << " ";
        }
        cout << '\n';
    }

}

int main(){
    
    ios_base::sync_with_stdio(false);

    freopen(INFILE, "r", stdin);
    freopen(OUTFILE, "w", stdout);

    cin.tie(nullptr);
    cout.tie(nullptr);

    solve();

    return 0;
}