Cod sursa(job #1800823)

Utilizator valentinoMoldovan Rares valentino Data 8 noiembrie 2016 10:03:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 kb
#include <fstream>
#include <vector>
#include <iostream>
#define NM 100003
using namespace std;

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

int n, m, use[NM], sol, v0[NM];
vector < int > v[NM];

void DFS(int nod)
{
    use[nod] = 1;
    for(int i = 0; i < v0[nod]; ++i)
    {
        if(!use[ v[ nod ][ i ] ]) DFS(v[ nod ][ i ]);
    }
}

int main()
{
    int x, y;
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y;
        v0[x]++;
        v0[y]++;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for(int i = 1; i <= n; ++i)
        if(!use[i]) sol++, DFS(i);
    g << sol << '\n';
}