Cod sursa(job #3368386)

Utilizator teogrecigrecioiu teo teogreci Data 14 octombrie 2026 13:11:23
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.69 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");

const int NMAX = 100005;

int n, m, x, y, no_cc;
vector<vector<int>> graph;
bool used[NMAX];

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

int main()
{
    f >> n >> m;
    graph.assign(n + 1, vector<int>());

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

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

    g << no_cc;
    return 0;
}