Cod sursa(job #589923)

Utilizator stay_awake77Cangea Catalina stay_awake77 Data 14 mai 2011 14:57:22
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.09 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
#include <cstring>
#define NMAX 100001
#define mp make_pair
#define pb push_back
#define nod1 first
#define nod2 second

using namespace std;

int N, M, i, j, x, y, Lowest[NMAX], Level[NMAX], T[NMAX], Written[NMAX];
vector< int > G[NMAX];
vector< vector < int > > Comp;
stack< pair< int, int > > Muchii;
bool USED[NMAX];

inline void MemComp( int X, int Y )
{
    vector< int > C;
    pair< int, int > Mct, M1 = mp( X, Y ), M2 = mp( Y, X );

    do
    {
        Mct = Muchii.top();
        C.pb( Mct.nod1 );
        C.pb( Mct.nod2 );
        Muchii.pop();
    }
    while( Mct != M1 && Mct != M2 );

    Comp.pb( C );
}

inline void DF( int NOD )
{
    USED[NOD] = true;
    Lowest[NOD] = Level[NOD];

    for( vector< int >::iterator it = G[NOD].begin(); it != G[NOD].end(); it++ )
    {
        if( *it != T[NOD] && Level[NOD] > Level[*it] )
            Muchii.push( mp( *it, NOD ) );

        if( !USED[*it] )
        {
            Level[*it] = Level[NOD] + 1;
            T[*it] = NOD;

            DF( *it );

            if( Lowest[NOD] > Lowest[*it] )
                Lowest[NOD] = Lowest[*it];

            if( Lowest[*it] >= Level[NOD] )
                MemComp( *it, NOD );
        }
        else if( *it != T[NOD] && Lowest[NOD] > Level[*it] )
            Lowest[NOD] = Level[*it];
    }
}

int main()
{
    ifstream in("biconex.in");
    ofstream out("biconex.out");

    in >> N >> M;
    while( M-- )
    {
        in >> x >> y;
        G[x].pb( y );
        G[y].pb( x );
    }

    memset( USED, false, sizeof(USED) );

    Level[1] = 1;
    DF( 1 );

    out << Comp.size() << '\n';
    for( i=0; i<Comp.size(); i++ )
    {
        for( j=0; j<Comp[i].size(); j++ )
            Written[Comp[i][j]] = i;

        for( j=0; j<Comp[i].size(); j++ )
            if( Written[Comp[i][j]] == i )
            {
                out << Comp[i][j] << ' ';
                Written[Comp[i][j]] = -1;
            }
        out << '\n';
    }

    return 0;
}