Cod sursa(job #3237091)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 4 iulie 2024 18:00:52
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.7 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 100005;
vector<int> graph[MAX];
bitset<MAX> visited;

void dfs(int node)
{
    visited[node] = 1;
    for (int next : graph[node])
        if (!visited[next])
            dfs(next);
}

int main()
{
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");
    int n, m;
    cin >> n >> m;

    for (int i = 1; i <= m; ++i)
    {
        int x, y;
        cin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

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

    cout << ans;

    return 0;
}