Cod sursa(job #3347670)

Utilizator tudorhTudor Horobeanu tudorh Data 17 martie 2026 19:19:05
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 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],c[nmax+1];

int low[nmax+1],d[nmax+1],cnt,timer;

stack<int>s;

bool stacked[nmax+1];

void get_comp(int nod){
    cnt++;
    int t;
    do{
        t=s.top();
        stacked[t]=0;
        s.pop();
        c[cnt].pb(t);
    }while(t!=nod);
}

void tarjan(int nod){
    low[nod]=d[nod]=++timer;
    stacked[nod]=1;
    s.push(nod);
    for(int i:v[nod]){
        if(stacked[i])
            low[nod]=min(low[nod],d[i]);
        else if(!d[i]){
            tarjan(i);
            low[nod]=min(low[nod],low[i]);
        }
    }
    if(low[nod]==d[nod])
        get_comp(nod);
}

int main()
{
    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);
    fout<<cnt<<'\n';
    for(int i=1;i<=cnt;i++){
        for(int j:c[i])
            fout<<j<<' ';
        fout<<'\n';
    }
    return 0;
}