Cod sursa(job #2789741)

Utilizator iancupoppPopp Iancu Alexandru iancupopp Data 27 octombrie 2021 21:28:18
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.57 kb
#include <fstream>
#include <vector>

using namespace std;

const int N = 1e5 + 5;

vector<int> gr[N];
bool viz[N];

void dfs(int nod) {
  viz[nod] = true;
  for (auto vec : gr[nod])
    if (!viz[vec])
      dfs(vec);
}
int main() {
  ifstream cin("dfs.in");
  ofstream cout("dfs.out");
  int n, m;
  cin >> n >> m;
  while (m--) {
    int x, y;
    cin >> x >> y;
    gr[x].push_back(y);
    gr[y].push_back(x);
  }
  cin.close();
  int ans = 0;
  for (int i = 1; i <= n; ++i)
    if (!viz[i]) {
      ++ans;
      dfs(i);
    }
  cout << ans << "\n";
  cout.close();
  return 0;
}