Cod sursa(job #3343816)

Utilizator tudorhTudor Horobeanu tudorh Data 28 februarie 2026 15:56:45
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define pb push_back

using namespace std;

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

const int nmax = 1e5;

vector<int>v[nmax+1],r[nmax+1];
int l[nmax+1],d[nmax+1],timer,comp;
stack<int>s;
bool on_stack[nmax+1];
void get_scc(int nod){
    comp++;
    int t=0;
    do{
        t=s.top();
        on_stack[t]=0;
        s.pop();
        r[comp].pb(t);
    }while(t!=nod);
}
void tarjan(int nod,int pr){
    s.push(nod);
    on_stack[nod]=1;
    d[nod]=++timer;
    l[nod]=d[nod];
    for(int i:v[nod]){
        if(on_stack[i])
            l[nod]=min(l[nod],d[i]);
        else if(!d[i]){
            tarjan(i,nod);
            l[nod]=min(l[nod],l[i]);
        }
    }
    if(l[nod]==d[nod])
        get_scc(nod);
}

int main() {
    ios_base::sync_with_stdio (false);
    cin.tie (nullptr);
    int n, m;
    fin >> n >> m;
    while (m--) {
        int st, dr;
        fin >> st >> dr;
        v[st].pb (dr);
    }
    for(int i=1;i<=n;i++)
        if(!d[i])
            tarjan(i,0);
    fout<<comp<<'\n';
    for(int i=1;i<=comp;i++){
        for(int j:r[i])
            fout<<j<<' ';
        fout<<'\n';
    }
    return 0;
}