Cod sursa(job #3307571)

Utilizator vralexRadu Vasilescu vralex Data 21 august 2025 17:59:32
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

// Space complexity: O(m) + O(n) + O(n) = O(m + n),
// given by the adjacency lists, the visited vector
// and the recursion stack - at most n stack frames
// at a time, where n = the number of nodes of the graph.

// Time complexity: O(n + m), given by the DFS calls and by reading
// the input.

vector<vector<int>> adj;
vector<bool> visited;

void dfs(int u) {
  visited[u] = true;
  for (int v : adj[u])
    if (!visited[v]) dfs(v);
}

int main() {
  int n, m, x, y;

  fin >> n >> m;

  adj.resize(n + 1);
  visited.assign(n + 1, false);
  for (int i = 1; i <= m; i++) {
    fin >> x >> y;
    adj[x].push_back(y);
    adj[y].push_back(x);
  }

  int count = 0;

  for (int v = 1; v <= n; v++)
    if (!visited[v]) {
      dfs(v);
      count++;
    }
  fout << count;
  return 0;
}