Cod sursa(job #3372791)

Utilizator StefanVVulpoiu Stefan StefanV Data 4 noiembrie 2026 23:39:31
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("biconex.in");
ofstream fout("biconex.out");

int n, m, x, y, timer, dfn[100005], low[100005], ct;
bool viz[100005];
vector <int> adj[100005], stiva, comp[100005];

void DFS(int nod, int tata)
{
    viz[nod] = true;
    timer++;
    dfn[nod] = timer;
    low[nod] = timer;
    stiva.push_back(nod);
    for ( int v : adj[nod] )
    {
        if (v == tata)
            continue;
        if (viz[v] == true)
            low[nod] = min(low[nod], dfn[v]);
        else
        {
            DFS(v, nod);
            low[nod] = min(low[nod], low[v]);
            if (low[v] >= dfn[nod])
            {
                ct++;
                int extras;
                do {
                    extras = stiva.back();
                    stiva.pop_back();
                    comp[ct].push_back(extras);
                } while (extras != v);

                comp[ct].push_back(nod);
            }
        }
    }
}

int main()
{
    fin >> n >> m;
    for ( int i=1; i<=m; i++ )
    {
        fin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    for (int i=1; i<=n; i++)
        if (dfn[i] == 0)
            DFS(i, 0);

    fout <<ct << "\n";
    for (int i=1; i<=ct; i++)
    {
        for (int nod : comp[i])
            fout << nod << " ";
        fout << "\n";
    }
    return 0;
}