Cod sursa(job #3369954)

Utilizator david_28Bordean David Ioan david_28 Data 22 octombrie 2026 17:44:55
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>

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

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

int n, m, nrc;
int st[100005], viz[100005], top;

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 a_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);
    }
    
    a_scc();
    
    fout << nrc << endl;
    
    for(int i = 1; i <= nrc; ++i) {
        for(int x : scc[i])
            fout << x << ' ';
        fout << endl;
    }
    
    return 0;
}