Cod sursa(job #2770840)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 23 august 2021 16:57:32
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
int N, M, ans;
vector<vector<int>>G;
vector<bool>viz;
void dfs(int nod) {
    viz[nod] = 1;
    for(auto it: G[nod]) {
        if(!viz[it]) {
            viz[it] = 1;
            dfs(it);
        }
    }
}
int main() {
    fin >> N >> M;
    G = vector<vector<int>>(N + 1);
    viz = vector<bool>(N + 1);
    for(int i = 1, x, y; i <= M; i++) {
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for(int i = 1; i <= N; i++) {
        if(!viz[i]) {
            ans++;
            dfs(i);
        }
    }
    fout << ans << '\n';
    return 0;
}