Cod sursa(job #3286808)

Utilizator stanciuvalentinStanciu-Tivlea Valentin Gabriel stanciuvalentin Data 14 martie 2025 18:09:20
Problema Componente tare conexe Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,k,x,y,r,low[100200],hi[100200];
vector <int> w[100200],edges[100200];
stack <int> st;

void tarjan(int x)
{
    st.push(x);
    low[x]=hi[x]=++k;
    for(auto y:edges[x])
    {
        if(hi[y])
            low[x]=min(low[x],hi[y]);
        else
            tarjan(y), low[x]=min(low[x],low[y]);
    }
    if(low[x]==hi[x])
    {
        r++;
        while(!st.empty() and st.top()!=x)
            w[r].push_back(st.top()), st.pop();
        w[r].push_back(x), st.pop();
    }
}

int32_t main()
{
    f>>n>>m;
    for(int i=1; i<=m; i++)
        f>>x>>y, edges[x].push_back(y);
    for(int i=1; i<=n; i++)
        if(hi[i]==0)
            k=0, tarjan(i);
    g<<r<<'\n';
    for(int i=1; i<=r; i++, g<<'\n')
        if(w[i].size())
            for(auto it:w[i])
                g<<it<<' ';
    return 0;
}