Cod sursa(job #3343631)

Utilizator stanciuvalentinStanciu-Tivlea Valentin Gabriel stanciuvalentin Data 27 februarie 2026 21:20:30
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,x,y,nr,k,viz[100200],low[100200],hi[100200];
vector <int> edges[100200], tedges[100200], rez[100200];
stack <int> st;

void tarjan(int x)
{
    st.push(x);
    viz[x]=1;
    low[x]=hi[x]=++k;
    for(auto y:edges[x])
        if(viz[y]==0)
            tarjan(y), low[x]=min(low[x],low[y]);
        else if(viz[y]==1)
            low[x]=min(low[x],hi[y]);
    if(low[x]==hi[x])
    {
        nr++;
        while(!st.empty() and st.top()!=x)
        {
            viz[st.top()]=2;
            rez[nr].push_back(st.top());
            st.pop();
        }
        viz[x]=2;
        rez[nr].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(viz[i]==0)
            tarjan(i);
    g<<nr<<'\n';
    for(int i=1; i<=nr; i++, g<<'\n')
        for(auto it:rez[i])
            g<<it<<' ';
    return 0;
}