Cod sursa(job #2340833)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 11 februarie 2019 09:49:25
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
#define INF 100005
#define Nmax 100005

using namespace std;

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

int n, m, x, y, comp;
int lv[Nmax], lmax[Nmax];
bitset <Nmax> seen;
vector <int> v[Nmax];
stack <int> st;
vector <int> sol[Nmax];

void getComp(int x, int tt)
{
    sol[comp].push_back(tt);
    while(!st.empty()&&st.top()!=x)
    {
        sol[comp].push_back(st.top());
        st.pop();
    }
    if(!st.empty())
    {
        sol[comp].push_back(x);
        st.pop();
    }
}

void dfs(int x, int tt, int r)
{
    seen[x]=1;
    lmax[x]=lv[x]=lv[tt]+1;
    for (int i = 0, l=v[x].size(); i < l; i++)
    {
        int y=v[x][i];
        if(y == tt) continue;
        if(seen[y] == 1)
        {
            lmax[x]=min(lmax[x], lv[y]);
            continue;
        }
        st.push(y);
        dfs(y, x, y);
        lmax[x]=min(lmax[x], lmax[y]);
        if(lmax[y]>=lv[x])
        {
            comp++;
            getComp(y, x);
        }
    }
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        f >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if(seen[i] == 0)
            dfs(i, 0, i);

    g << comp << '\n';
    for (int i = 1; i <= comp; i++)
    {
        for (int j = 0; j < sol[i].size(); j++)
            g << sol[i][j] << " ";
        g << '\n';
    }

    return 0;
}