Cod sursa(job #2647461)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 4 septembrie 2020 18:32:44
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.57 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 1e5;

int N, M, nrc;
vector <int> g[NMAX + 5];

bool d[NMAX + 5];

void dfs(int node)
{
    d[node] = 1;

    for(auto it : g[node])
        if(!d[it])
            dfs(it);
}

int main()
{
    fin >> N >> M;

    for(int i = 1; i <= M; i++) {

        int a, b; fin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);

    }

    for(int i = 1; i <= N; i++)
    if(!d[i]) {
        nrc++;
        dfs(i);
    }

    fout << nrc;

    return 0;
}