Cod sursa(job #3366238)

Utilizator angelaAngela Visuian angela Data 30 septembrie 2026 09:35:57
Problema Componente biconexe Scor 46
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <vector>
#include <fstream>
#include <set>
#include <stack>
using namespace std;

using SI  = set<int>;
using VI  = vector<int>;
using VVI = vector<VI>;
using VSI = vector<SI>;
ifstream fin("biconex.in");
ofstream fout("biconex.out");

VVI adj;
VI index, low;
int idx;
stack<int> st;
VSI cbc;
int n, m;

void AddComp(int nod)
{
    SI comp;
    while (!st.empty())
    {
        comp.insert(st.top());
        if (st.top() == nod)
            break;
        st.pop(); // nu mai sterg nodul de plecare; acesta poate sa faca parte din mai multe ctc
    }

    cbc.push_back(comp);
}

void Dfs(int x, int fa)
{
    index[x] = low[x] = ++idx;
    st.push(x);
    for (auto y : adj[x])
    {
        if (y == fa)
            continue;
        if (!index[y])
        {
            Dfs(y, x);
            low[x] = min(low[x], low[y]);
            if (low[y] >= index[x])
                AddComp(x);
        }
        else
            low[x] = min(low[x], index[y]);
    }
}

void CBC()
{
    for (int x = 1; x <= n; ++x)
        if (!index[x])
        {

            Dfs(x, 0);
            st = stack<int>();
        }
}

int main()
{
    fin >> n >> m;
    int u, v;
    adj = VVI(n + 1);
    index = low = VI(n + 1);
    for (int i = 1; i <= m; ++i)
    {
        fin >> u >> v;
        adj[v].push_back(u);
        adj[u].push_back(v);
    }

    CBC();
    fout << cbc.size() << '\n';
    for (auto c : cbc)
    {
        for (auto x : c)
            fout << x << " ";
        fout << '\n';
    }

    return 0;
}