Cod sursa(job #1108209)

Utilizator Athena99Anghel Anca Athena99 Data 15 februarie 2014 14:54:22
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax= 100000;

bool u[nmax+1];
vector <int> v[nmax+1];

void dfs( int x ) {
    u[x]= 1;
    for ( vector <int>::iterator it= v[x].begin(); it!=v[x].end(); ++it ) {
        if ( u[*it]==0 ) {
            dfs(*it);
        }
    }
}

int main(  ) {
    int n, m;
    fin>>n>>m;
    for ( ; m; --m ) {
        int x, y;
        fin>>x>>y;
        v[x].push_back(y);
        v[y].push_back(x);
    }

    int sol= 0;
    for ( int i= 1; i<=n; ++i ) {
        if ( u[i]==0 ) {
            ++sol;
            dfs(i);
        }
    }

    fout<<sol<<"\n";

    return 0;
}