Cod sursa(job #3293462)

Utilizator robert.barbu27robert barbu robert.barbu27 Data 11 aprilie 2025 18:46:07
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("biconex.in");
ofstream fout("biconex.out");
vector<int> adj[100005];
int vizitat[1000005];
int low[100005];  // care e cel mai devreme nod in care putem ajunge din nodul i
int disc[100005]; // cand am descoperit nodul i;
int timp = 0;
stack<int> s;
vector<vector<int>> components;
void dfs(int node, int parinte)
{
    vizitat[node] = true;
    disc[node] = ++timp;
    low[node] = disc[node];
    s.push(node);
    for (auto x : adj[node])
    {
        if (vizitat[x] == 0)
        {
            dfs(x, node);
            low[node] = min(low[node], low[x]);
            if (low[x] >= disc[node])
            {
                vector<int> componenta;
                while (s.top() != x)
                {
                    componenta.push_back(s.top());
                    s.pop();
                }
                componenta.push_back(x);
                s.pop();
                componenta.push_back(node);
                components.push_back(componenta);
            }
        }
        else
        {
            if (x != parinte)
            {
                low[node] = min(low[node], disc[x]);
            }
        }
    }
}
int main()
{
    int N,M;
    fin>>N>>M;
    for(int i=1;i<=M;i++){
        int x,y;
        fin>>x>>y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    dfs(1,0);
    fout<<components.size()<<'\n';
    for(auto it:components){
        for(auto it2:it){
            fout<<it2<<" ";
        }
        fout<<'\n';
    }
}