Cod sursa(job #2863525)

Utilizator DajaMihaiDaja Mihai DajaMihai Data 6 martie 2022 20:31:29
Problema Parcurgere DFS - componente conexe Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <fstream>
#include <vector>

#define MAX_N 100001

using namespace std;

vector<int> graph[MAX_N];
int subset[MAX_N];


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


void addEdge (int a, int b){
  graph[a].push_back(b);
  graph[b].push_back(a);
}


void dfs(int a, int noSubset){
  subset[a] = noSubset;

  for (int neighbour : graph[a])
    if (subset[neighbour] == 0)
      dfs(neighbour, noSubset);
}


int main(){
  int n, m;
  in >> n >> m;

  int a, b;
  for (int i = 0; i < m; i ++){
    in >> a >> b;
    addEdge(a, b);
  }

  int noSubsets = 0;
  for (int i = 0; i < n; i ++){
    if (subset[i] == 0){
      dfs(i, noSubsets + 1);
      noSubsets ++;
    }
  }
  out << noSubsets;
}