Cod sursa(job #3285088)

Utilizator Dia3141Costea Diana Stefania Dia3141 Data 12 martie 2025 15:09:56
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
#include <stack>
#define nmax (int)(1e5+1)
using namespace std;
ifstream cin("ctc.in");
ofstream cout("ctc.out");
int n,m,x,y,k,niv[nmax],minlv[nmax];
bool viz[nmax],in[nmax];
vector<int>v[nmax],aux;
vector<vector<int>>sol;
stack<int>s;
void dfs(int nod){
    viz[nod]=1;
    s.push(nod);
    in[nod]=1;
    minlv[nod]=niv[nod]=++k;
    for(auto i:v[nod])
        if(!viz[i]){
            dfs(i);
            if(in[i])
                minlv[nod]=min(minlv[nod],minlv[i]);
        }else if(in[i])
            minlv[nod]=min(minlv[nod],niv[i]);
    if(niv[nod]==minlv[nod]){
        aux.clear();
        while(!s.empty()&&s.top()!=nod){
            aux.push_back(s.top());
            in[s.top()]=0;
            s.pop();
        }
        in[nod]=0;
        s.pop();
        aux.push_back(nod);
        sol.push_back(aux);
    }
}
signed main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        cin>>x>>y;
        v[x].push_back(y);
    }
    for(int i=1;i<=n;i++)
        if(!viz[i])
            dfs(i);
    cout<<sol.size()<<'\n';
    for(auto i:sol){
        for(auto j:i)
            cout<<j<<" ";
        cout<<'\n';
    }
    return 0;
}
/// Tarjan