Cod sursa(job #3120417)

Utilizator ioana3317ioanapopescu ioana3317 Data 6 aprilie 2023 16:20:54
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int N = 1e5 +2, M= 2e5+2;
int n, m, v2[N];
bool v[N];
vector <int> pred[N];
vector <int> urm[N];
vector <int> r[N];
stack <int> stiv;

void dfs1(int nd){
    v[nd] = 1;
    for( auto i: urm[nd] ){
        if( v[i] == 0){
            dfs1(i);
        }
    }
    stiv.push(nd);
}

void dfs2(int nd, int secret){
    v2[nd] = secret;
    for(auto i: pred[nd] ){
        if(v2[i] == 0){
            dfs2(i, secret);
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i=1; i<=m; i++){
        int x, y;
        in >> x >> y;
        urm[x].push_back(y);
        pred[y].push_back(x);
    }

    for(int i=1; i<=n; i++){
        if(v[i] == 0){
            dfs1(i);
        }
    }

    int cnt=0;
    while ( !stiv.empty() ){
        int nd =  stiv.top();
        stiv.pop();
        if(v2[nd] == 0){
            cnt++;
            dfs2(nd, cnt);
        }
    }

    for(int i=1;  i<=n; i++){
        r[v2[i]].push_back(i);
    }

    out << cnt << "\n";
    for(int i=1; i<=cnt; i++){
        for(auto j: r[i] ){
            out << j << " ";
        }
        out << "\n";
    }


    return 0;
}