Cod sursa(job #2610354)

Utilizator Miruna_OrzataOrzata Miruna-Narcisa Miruna_Orzata Data 4 mai 2020 19:18:29
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100009 // numar maxim de noduri

class Task {
public:
  void solve() {
    read_input();
    get_result();
    print_output();
  }

private:
  int n, m;
  vector<int> adj[NMAX];
  int nr_conex_components = 0;

  void read_input() {
    ifstream fin("dfs.in");
    fin >> n >> m;

    for (int i = 1; i <= m; ++i) {
      int x, y;
      fin >> x >> y;

      adj[x].push_back(y);
      adj[y].push_back(x);
    }
    fin.close();
  }

  void get_result() {
    do_dfs();
  }

  void do_dfs() {
    vector<int> visited(n + 1);

    for (int i = 1; i <= n; ++i) {
      visited[i] = 0;
    }

    for (int i = 1; i <= n; ++i) {
      if (!visited[i]) {
        nr_conex_components++;
        dfs(i, visited);
      }
    }
  }

  void dfs(int node, vector<int> &visited) {
    visited[node] = 1;

    for (auto &it : adj[node]) {
      if (!visited[it]) {
        dfs(it, visited);
      }
    }

  }

  void print_output() {
    ofstream fout("dfs.out");
    fout << nr_conex_components;
    fout.close();
    }
};


int main() {
  Task *task = new Task();
  task->solve();
  delete task;

  return 0;
}