Cod sursa(job #2719743)

Utilizator danhHarangus Dan danh Data 10 martie 2021 11:31:35
Problema Componente biconexe Scor 46
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

const int NMAX = 100005;

vector<int> v[NMAX];
stack<int> st;
int low_link[NMAX];
int id[NMAX];
int cnt;

vector<vector<int> >components;

void DFS(int x, int parent)
{
    low_link[x] = id[x] = ++cnt;
    st.push(x);
    for(auto node : v[x])
    {
        if(node != parent)
        {
            if(id[node] == 0)
            {
                DFS(node, x);
                low_link[x] = min(low_link[x], low_link[node]);
                if(low_link[node] >= id[x])
                {
                    vector<int> new_comp;
                    while(st.top() != x)
                    {
                        new_comp.push_back(st.top());
                        st.pop();
                    }
                    new_comp.push_back(x);
                    components.push_back(new_comp);
                }
            }
            else
            {
                low_link[x] = min(low_link[x], id[node]);
            }
        }
    }
}

int main()
{
    int x, y, i, j, n, m;

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

    DFS(1, 0);

    fout<<components.size()<<'\n';
    for(auto c : components)
    {
        for(auto el : c)
        {
            fout<<el<<' ';
        }
        fout<<'\n';
    }

    fin.close();
    fout.close();
    return 0;
}