Cod sursa(job #2156377)

Utilizator edi9876Negescu Eduard Mihai edi9876 Data 8 martie 2018 18:11:37
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>

using namespace std;

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

#define debug(a)\
{\
    out << #a << ' ' << a << '\n';\
}

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

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

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

int nr_componente()
{
    int rez = 0;
    for(int i = 1; i <= n; i++)
    {
        if(!viz[i])
        {
            dfs(i);
            ++rez;
        }
    }
    return rez;
}

int main()
{
    citire();
    out << nr_componente() << '\n';
    return 0;
}