Cod sursa(job #1308680)

Utilizator gedicaAlpaca Gedit gedica Data 4 ianuarie 2015 16:03:02
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.72 kb
#include <fstream>
#include <vector>

using namespace std;

const int NMAX= 100000;

ifstream in( "dfs.in" );
ofstream out( "dfs.out" );

vector <int> g[NMAX+1];
bool viz[NMAX+1];

void DFS( int X )
{
    viz[X]= 1;
    for( int i= 0; i<(int)g[X].size(); ++i )
    {
        if( viz[g[X][i]]==0 ) DFS( g[X][i] );
    }
}

int main(  )
{
    int N, M;

    in >> N >> M;

    int x, y;

    for( int i= 1; i<=M; ++i )
    {
        in >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    int nr= 0;

    for( int i= 1; i<=N; ++i )
    {
        if( viz[i]==0 )
        {
            ++nr;
            DFS( i );
        }
    }

    out << nr << '\n';

    return 0;
}