Cod sursa(job #2666457)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 1 noiembrie 2020 21:55:39
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <stack>
#include <set>

using namespace std;

ifstream f("biconex.in");
ofstream g("biconex.out");

int n, m;

vector < vector < int > > adj;

vector < int > disc, low;

vector < set < int > > comp;

stack < pair < int, int > > s;

set < int > newComp(stack < pair < int, int > > &s, pair < int, int > p)
{
    set < int > c;

    while (s.top() != p)
    {
        c.insert(s.top().first);
        c.insert(s.top().second);
        s.pop();
    }

    c.insert(s.top().first);
    c.insert(s.top().second);
    s.pop();

    return c;
}

void dfs(int node)
{
    static int ord = 1;
    disc[node] = low[node] = ord++;

    for (auto it : adj[node])
        if (!disc[it])
        {
            s.push({node, it});

            dfs(it);
            low[node] = min(low[node], low[it]);

            if (disc[node] <= low[it])
                comp.push_back(newComp(s, {node, it}));
        }
        else
            low[node] = min(low[node], disc[it]);
}

int main()
{
    f >> n >> m;

    adj.resize(n + 1);
    low.resize(n + 1);
    disc.resize(n + 1);

    while (m--)
    {
        int x, y; f >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    dfs(1);

    g << comp.size() << "\n";
    for (auto c : comp)
    {
        for (auto node : c)
            g << node << " ";
        g << "\n";
    }

    return 0;
}