Cod sursa(job #2863522)

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

#define MAX_N 100000

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])
      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]){
      dfs(i, noSubsets + 1);
      noSubsets ++;
    }
  }
  out << noSubsets;
}