Cod sursa(job #2863534)

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

#define MAX_N 100001

using namespace std;

vector<int> graph[MAX_N];
bool 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 initialize() {
  for(int i = 0;i < MAX_N;++i)
    subset[i] = false;
}

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

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


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