Cod sursa(job #3307628)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 22 august 2025 12:33:13
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;
int low[100005], viz[100005], n, m, x, y, nr, nrc, i;
vector <int> v[100005], nrcomp[100005];
stack <int> st;
bool onstack[100005];
void dfs(int nod)
{
    viz[nod]=low[nod]=++nr;
    st.push(nod);
    onstack[nod]=true;
    for(auto i: v[nod])
        if(viz[i]==0)
        {
            dfs(i);
            low[nod]=min(low[nod], low[i]);
        }
        else
            if(onstack[i])
            low[nod]=min(low[nod], viz[i]);
    if(viz[nod]==low[nod])
    {
        nrc++;
        while(nod!=st.top())
        {
            onstack[st.top()]=false;
            nrcomp[nrc].push_back(st.top());
            st.pop();
        }
        onstack[nod]=false;
        nrcomp[nrc].push_back(st.top());
        st.pop();
    }
}
int main()
{
    cin>>n>>m;
    for(i=1; i<=n; i++)
        onstack[i]=false;
    while(m--)
    {
        cin>>x>>y;
        v[x].push_back(y);
    }
    for(i=1; i<=n; i++)
        if(viz[i]==0)
            dfs(i);
    cout<<nrc<<'\n';
    for(i=1; i<=nrc; i++)
    {
        for(auto j: nrcomp[i])
            cout<<j<<" ";
        cout<<'\n';
    }


    return 0;
}