Cod sursa(job #1650702)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 11 martie 2016 19:56:45
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

using VI = vector<int>;
using VII = vector<VI>;

ifstream is("biconex.in");
ofstream os("biconex.out");

void Df(int x, int tata, int niv);
void Write();
void Read();

int n, m;
VII G, comp;
VI l, nv, c;
vector<bool> v;
stack<pair<int, int>> s;


int main()
{
    Read();
    Df(1, 0, 0);
    Write();

    is.close();
    os.close();
    return 0;
}

void Df(int x, int tata, int niv)
{
    nv[x] = l[x] = niv + 1;
    v[x] = true;
    for ( const auto& y : G[x] )
    {
        if ( y == tata )
            continue;
        if ( !v[y] )
        {
            s.push({x, y});
            Df(y, x, nv[x]);
            l[x] = min(l[x], l[y]);
            if ( l[y] >= nv[x] )
            {
                c.clear();
                int a, b;
                do
                {
                    a = s.top().first;
                    b = s.top().second;
                    s.pop();
                    c.push_back(a);
                    c.push_back(b);
                } while ( a != x && b != y );
                comp.push_back(c);
            }
        }
        else
            l[x] = min(l[x], nv[y]);
    }
}
void Write()
{
    os << comp.size() << '\n';
    for ( auto& i : comp )
    {
        sort(i.begin(), i.end());
        i.erase(unique(i.begin(), i.end()), i.end());
        for ( const auto& j : i )
            os << j << ' ';
        os << '\n';
    }
}
void Read()
{
    is >> n >> m;
    l = nv = VI(n + 1);
    v = vector<bool>(n + 1);
    G = VII(n + 1);
    for ( int i = 1, x, y; i <= m; ++i )
    {
        is >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}