Cod sursa(job #2138319)

Utilizator CryshanaGanea Carina Cryshana Data 21 februarie 2018 15:51:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;

const int N = 100001;
vector <int> a[N];
int n, m, c;
bool viz[N];

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

void citire ()
{
    fin >> n >> m;
    int x, y;
    for ( int i = 0 ; i < m ; i++ )
    {
        fin >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    fin.close();
}

void dfs ( int x )
{
    viz[x] = true;
    int y;
    for ( int i = 0 ; i < a[x].size() ; i++ )
    {
        y = a[x][i];
        if ( !viz[y] )
        {
            dfs(y);
        }
    }
}

int main()
{
    citire();
    for ( int i = 1 ; i <= n ; i ++ )
    {
        if ( !viz[i] )
        {
            c ++;
        }
        dfs(i);
    }
    fout << c;
    return 0;
}