Cod sursa(job #2976821)

Utilizator Luca_Miscocilucainfoarena Luca_Miscoci Data 10 februarie 2023 08:50:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.66 kb
#include <fstream>
#include <vector>
using namespace std;

const int nmax = 1e5;

bool marked[nmax + 1];
vector <int> graf[nmax + 1];

void dfs (int node){
  marked[node] = true;
  for (auto neighbour : graf[node]){
    if (!marked[neighbour])
      dfs(neighbour);
  }
}

int main(){

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

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

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

  fout << cnt;
  return 0;
}