Cod sursa(job #3374291)

Utilizator AbRobertAbabei Robert-Petronel AbRobert Data 8 noiembrie 2026 22:07:03
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <vector>
#include <fstream>
#include <algorithm>
#include <bitset>
#include <stack>
#include <algorithm>

int n, m;
std::vector<int> L[100001], timp_vizitare, low;
std::vector<std::vector<int>> componente;
std::stack<int> stiva;
int timp = 0;

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

void DFS(int x, int p = -1)
{
    timp_vizitare[x] = low[x] = ++timp;
    stiva.push(x);

    for (int e : L[x])
        if (e == p) continue; // sa nu ne intoarcem inapoi pe muchii
        else if (timp_vizitare[e]) // am vizitat deja nodul
            low[x] = std::min(low[x], timp_vizitare[e]);
        else
        {
            DFS(e, x);
            low[x] = std::min(low[x], low[e]);
            if (low[e] >= timp_vizitare[x])
            {
                componente.push_back({});
                int nod;
                do
                {
                    nod = stiva.top();
                    stiva.pop();
                    componente.back().push_back(nod);
                } while (nod != e);
                componente.back().push_back(x);
            }
        }
}

int main()
{
    int x, y;
    fin >> n >> m;
    timp_vizitare.resize(n + 1, 0);
    low.resize(n + 1, 0);

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

    for (int i = 1; i <= n; i++)
        if (!timp_vizitare[i])
            DFS(i);

    fout << componente.size() << "\n";
    for (std::vector<int>& x : componente)
    {
        std::sort(x.begin(), x.end());
        for (int e : x)
            fout << e << " ";
        fout << "\n";
    }
}