Cod sursa(job #447403)

Utilizator alexandru92alexandru alexandru92 Data 28 aprilie 2010 17:07:34
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on April 28, 2010, 4:55 PM
 */
#include <stack>
#include <vector>
#include <cstdlib>
#include <fstream>
#define Nmax 100011

/*
 * 
 */
using namespace std;
int uz[Nmax];
stack< int > S;
vector< int > G[Nmax];
vector< int >::const_iterator it, iend;
inline void DFS( int x )
{
    while( true )
    {
        for( it=G[x].begin()+uz[x], iend=G[x].end(); it < iend; ++it )
            if( !uz[*it] )
                break;
        uz[x]=it-G[x].begin()+1;
        if( it >= iend )
            break;
        S.push(x);
        x=*it;
    }
}
int main(int argc, char** argv)
{
    int N, M, x, y, z;
    ifstream in( "dfs.in" );
    for( in>>N>>M; M; --M )
    {
        in>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for( y=0, x=1; x <= N; ++x )
        if( !uz[x] )
        {
            ++y;
            z=x;
            while( true )
            {
                DFS(z);
                if( S.empty() )
                    break;
                z=S.top(); S.pop();
            }
        }
    ofstream out( "dfs.out" );
    out<<y<<'\n';
    return (EXIT_SUCCESS);
}