Cod sursa(job #2981188)

Utilizator rapidu36Victor Manz rapidu36 Data 17 februarie 2023 14:54:35
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

const int N = 1e5;

vector <int> a[N+1];
vector <vector <int>> cbc;
stack <int> stiva;
bool art[N+1];
int t_in[N+1], t_min[N+1], timp;

void adauga_cbc(int x, int y, vector <int> &v)
{
    while (stiva.top() != y)
    {
        v.push_back(stiva.top());
        stiva.pop();
    }
    v.push_back(y);
    stiva.pop();
    v.push_back(x);
}

void dfs(int x, int t)
{
    t_in[x] = t_min[x] = ++timp;
    stiva.push(x);
    for (auto y: a[x])
    {
        if (y == t)
        {
            continue;
        }
        if (t_in[y] == 0)///y este fiu al lui x in arborele dfs
        {
            dfs(y, x);
            t_min[x] = min(t_min[x], t_min[y]);
            ///y nu apartine unui ciclu elem. care contine un stramos al lui x
            if (t_min[y] >= t_in[x])
            {
                vector <int> c;
                adauga_cbc(x, y, c);
                cbc.push_back(c);
            }
        }
        else///{x,y} e muchie de intoarcere
        {
            t_min[x] = min(t_min[x], t_in[y]);
        }
    }
}

int main()
{
    ifstream in("biconex.in");
    ofstream out("biconex.out");
    int n, m;
    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);
    }
    for (int i = 1; i <= n; i++)
    {
        if (t_in[i] == 0)
        {
            dfs(i, 0);
        }
    }
    out << cbc.size() << "\n";
    for (auto c: cbc)
    {
        for (auto x: c)
        {
            out << x << " ";
        }
        out << "\n";
    }
    in.close();
    out.close();
    return 0;
}