Cod sursa(job #2937924)

Utilizator IanisBelu Ianis Ianis Data 11 noiembrie 2022 13:31:24
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.77 kb
#include <bits/stdc++.h>

using namespace std;

#ifdef LOCAL
ifstream fin("input.txt");
#define fout cout
#else
ifstream fin("dfs.in");
ofstream fout("dfs.out");
#endif

const int NMAX = 1e5+5;

int n, m;
vector<int> g[NMAX];
bool viz[NMAX];

void add_edge(int x, int y) {
    g[x].push_back(y);
    g[y].push_back(x);
}

void dfs(int u) {
    for (auto v : g[u]) {
        if (!viz[v]) {
            viz[v] = true;
            dfs(v);
        }
    }
}

int main() {
    fin >> n >> m;
    int x, y;
    while (m--) {
        fin >> x >> y;
        add_edge(x, y);
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (!viz[i]) {
            dfs(i);
            ans++;
        }
    }
    fout << ans;
    return 0;
}