Cod sursa(job #3350662)

Utilizator Alex_at_gameIustin-Alexandru Frateanu Alex_at_game Data 11 aprilie 2026 17:47:58
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(v) begin(v), end(v)
#define al(v, l, r) begin(v) + l, begin(v) + r + 1
#define sz(v) (int)v.size()
#define pb push_back
#define pob pop_back
#define fs first
#define sd second

constexpr int inf = 2e9;
constexpr ll infll = 4e18;
constexpr int N = 1e5 + 5;

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

void dfs(int x) {
    viz[x] = true;
    for (int y : g[x]) {
        if (viz[y]) {
            continue;
        }

        dfs(y);
    }
}

signed main() {
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    freopen("dfs.in", "r", stdin);
    freopen("dfs.out", "w", stdout);

    cin >> n >> m;
    for (int i = 0, x, y; i < m; ++i) {
        cin >> x >> y;
        g[x].pb(y);
        g[y].pb(x);
    }

    for (int i = 1; i <= n; ++i) {
        if (!viz[i]) {
            ans++;
            dfs(i);
        }
    }

    cout << ans << "\n";
}