Cod sursa(job #3167112)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 9 noiembrie 2023 23:47:58
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#include <random>
#include <chrono>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const char nl = '\n';
const char sp = ' ';
const int inf = 0x3f3f3f3f;
const long long INF = 1000000000000000000;
const int mod = 1e9 + 7;
const char out[2][4]{ "NO", "YES" };
#define all(A) A.begin(), A.end()
using ll = long long;
ifstream fin("dfs.in");
ofstream fout("dfs.out");

#define variableName(var) #var
#define __debug(var) cout << #var << " = " << var << '\n'
inline int rint(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }

const int nmax = 1e5;
int n, m;
vector<int> g[nmax + 5];
bool vis[nmax + 5]{ 0 };

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

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n >> m;
    for (int i = 1; i <= m; ++i) {
        int u, v;
        fin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        if (!vis[i]) {
            dfs(i);
            ans++;
        }
    }
    fout << ans;
}