Cod sursa(job #3239883)

Utilizator ChopinFLazar Alexandru ChopinF Data 8 august 2024 15:33:15
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <bits/stdc++.h>
#include <vector>
using namespace std;
std::string file = "dfs";
std::ifstream fin(file + ".in");
std::ofstream fout(file + ".out");
// #define fin std::cin
// #define fout std::cout
int n, m;
std::vector<std::vector<int>> gf;
std::vector<bool> vis;
void dfs(int node) {
  vis[node] = true;
  for (const auto &nextNode : gf[node]) {
    if (!vis[nextNode])
      dfs(nextNode);
  }
}
int32_t main(int32_t argc, char *argv[]) {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);
  fin >> n >> m;
  gf.resize(n + 1);
  vis.resize(n + 1, false);
  for (int i = 0; i < m; ++i) {
    int a, b;
    fin >> a >> b;
    gf[a].push_back(b);
  }

  int cnt = 0;
  for (int i = 1; i <= n; ++i) {
    if (!vis[i]) {
      ++cnt;
      dfs(i);
    }
  }
  fout << cnt << "\n";
  return 0;
}