Cod sursa(job #1754622)

Utilizator antracodRadu Teodor antracod Data 8 septembrie 2016 15:00:27
Problema Parcurgere DFS - componente conexe Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

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

const int nmax = 100000;

vector <int> g[nmax+1];

bool b[nmax+1];

void dfs( int x ) {
    b[x] = 1;
    for ( int i = 0; i < (int)g[x].size(); ++ i ) {
        if ( b[g[x][i]] == 0 ) {
            dfs(g[x][i]);
        }
    }
}

int main()
{
    int n, m;
    in >> n >> m;
    for ( int i = 1; i <= n; ++ i ) {
        int x, y;
        in >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    int sol = 0;
    for ( int i = 1; i <= n; ++ i ) {
        if ( b[i] == 0 ) {
            ++ sol;
            dfs(i);
        }
    }
    out << sol << "\n";
    return 0;
}