Cod sursa(job #2811675)

Utilizator rapidu36Victor Manz rapidu36 Data 2 decembrie 2021 20:56:10
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <vector>
#include <stack>
#include <set>

using namespace std;

const int N = 1e5 + 1;

int n, m, t[N], t_min[N], timp, n_cbc;
vector <int> a[N];
set <int> cbc[N];
stack <pair <int, int>> stiva;

/*
void adauga_cbc(pair <int, int> e)
{
    vector <int> comp;
    while (stiva.top().first != e.first || stiva.top().second != e.second)
    {
        comp.push_back(stiva.top().first);
        comp.push_back(stiva.top().second);
        stiva.pop();
    }
    comp.push_back(stiva.top().first);
    comp.push_back(stiva.top().second);
    stiva.pop();
    sort(comp.begin(), comp.end());
    n_cbc++;
    cbc[n_cbc].push_back(comp[0]);
    for (size_t i = 1; i < comp.size(); i++)
    {
        if (comp[i] != comp[i-1])
        {
            cbc[n_cbc].push_back(comp[i]);
        }
    }
}
*/

void adauga_cbc(pair <int, int> e)
{
    n_cbc++;
    while (stiva.top().first != e.first || stiva.top().second != e.second)
    {
        cbc[n_cbc].insert(stiva.top().first);
        cbc[n_cbc].insert(stiva.top().second);
        stiva.pop();
    }
    cbc[n_cbc].insert(stiva.top().first);
    cbc[n_cbc].insert(stiva.top().second);
    stiva.pop();
}

void dfs(int x, int tata)
{
    t_min[x] = t[x] = ++timp;
    int nr_fii = 0;
    for (auto y: a[x])
    {
        if (t[y] == 0)
        {
            nr_fii++;
            stiva.push({x, y});
            dfs(y, x);
            t_min[x] = min(t_min[x], t_min[y]);
            if (t_min[y] >= t[x])
            {
                //p_art.push_back(x);///x este punct de articulatie
                adauga_cbc({x, y});
            }
        }
        else if (y != tata)
        {
            t_min[x] = min(t_min[x], t[y]);
        }
    }

}

int main()
{
    ifstream in("biconex.in");
    ofstream out("biconex.out");
    in >> n >> m;
    for (int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    in.close();
    for (int i = 1; i <= n; i++)
    {
        if (t[i] == 0)
        {
            dfs(i, 0);
        }
    }
    out << n_cbc << "\n";
    for (int i = 1; i <= n_cbc; i++)
    {
        for (auto x: cbc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}