Cod sursa(job #3369944)

Utilizator hgrgrgtgrihstrandrei o. hgrgrgtgrihstr Data 22 octombrie 2026 17:16:15
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

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

vector<int> h[100003];
vector<int> g[100003];
vector<int> scc[100003];

int n, m, nrc, top;
int st[1000003];
bool viz[100003];

void dfs(int n) {
    viz[n] = true;
    
    for(int i : h[n])
        if(!viz[i])
            dfs(i);
            
    st[++top] = n;
}

void dfs2(int n) {
    viz[n] = false;
    for(int i : g[n])
        if(viz[i])
           dfs2(i);
    scc[nrc].push_back(n);
}

void do_scc() {
    for(int i = 1; i <= n; ++i)
        if(!viz[i])
            dfs(i);
    for(int i = n; i > 0; --i)
        if(viz[st[i]]) {
            ++nrc;
            dfs2(st[i]);
        }
    
}

int main() {
    fin >> n >> m;
    
    for(int i = 0; i < m; ++i) {
        int x, y; fin >> x >> y;
        h[x].push_back(y);
        g[y].push_back(x);
    }
    
    do_scc();
    
    fout << nrc << endl;
    
    for(int i = 1; i <= nrc; ++i) {
        for(int x : scc[i])
            fout << x << ' ';
        fout << endl;
    }
    
    return 0;
}