Cod sursa(job #3147324)

Utilizator Traian_7109Traian Mihai Danciu Traian_7109 Data 25 august 2023 18:39:43
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long 
#define ld long double
#define pii pair<int, int>
#define pll pair<ll, ll>
#define pb push_back
#define eb emplace_back

using namespace std;

signed main()
{
    #ifndef TEST 
        freopen("dfs.in", "r", stdin);
        freopen("dfs.out", "w", stdout);
    #endif
    ios_base :: sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    int n, m;
    cin >> n >> m;
    vector<vector<int>> g(n + 1);
    while (m--)
    {
        int u, v;
        cin >> u >> v;
        g[u].pb(v);
        g[v].pb(u);
    }
    vector<bool> visited(n + 1, false);
    function<void(int)> dfs = [&](int u)
    {
        visited[u] = true;
        for (auto v : g[u])
        {
            if (!visited[v])
            {
                dfs(v);
            }
        }
    };
    int ans = 0;
    for (int i = 1; i <= n; i++)
    {
        if (!visited[i])
        {
            ans++;
            dfs(i);
        }
    }
    cout << ans;
    return 0;
}