Cod sursa(job #3271098)

Utilizator bostanlucastefanBostan Luca-Stefan bostanlucastefan Data 25 ianuarie 2025 10:19:09
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <algorithm>
#include <fstream>
#include <vector>
#include <stack>
#define FAST ios_base::sync_with_stdio(false);

using namespace std;

ifstream cin("ctc.in");
ofstream cout("ctc.out");

const int N=1e5+2;

stack<int> s;
int n,m,Time,i;
vector<int> g[N];
int low[N],disc[N];
vector<vector<int>> ans;

void dfs(int u)
{
    low[u]=disc[u]=++Time;
    s.push(u);
    for(auto v:g[u])
    {
        if(!disc[v])
            dfs(v);
        if(disc[v]>0)
            low[u]=min(low[u],low[v]);
    }
    if(low[u]==disc[u])
    {
        vector<int> th;
        int vf=0;
        while(vf!=u)
        {
            vf=s.top();
            s.pop();
            th.push_back(vf);
            disc[vf]=-1;
        }
        ans.push_back(th);
    }
}

int main()
{
    FAST
    cin>>n>>m;
    for(i=1; i<=m; i++)
    {
        int x,y;
        cin>>x>>y;
        g[x].push_back(y);
    }
    
    Time=0;
    for(i=1; i<=n; i++)
        if(!disc[i])
            dfs(i);
    
    cout<<ans.size()<<'\n';  
    for(auto in:ans)
    {
        for(auto i:in)
            cout<<i<<' ';
        cout<<'\n';
    }
    return 0;
}