Cod sursa(job #1435846)

Utilizator o_micBianca Costin o_mic Data 14 mai 2015 18:21:17
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <set>
#define DN 100005
#define LL long long
using namespace std;

vector <int> gr[DN];
int viz[DN];

void dfs(int node){
  for(int i = 0; i < gr[node].size(); ++i){
    if(!viz[gr[node][i]]){
      viz[gr[node][i]] = 1;
      dfs(gr[node][i]);
    }
  }
}

int main() {
  int n, m, x, y, res = 0;
  ifstream fin("dfs.in");
  ofstream fout("dfs.out");
  fin >> n >> m;
  for(int i = 0; i < m; ++i){
    fin >> x >> y;
    gr[x].push_back(y);
    gr[y].push_back(x);
  }
  for(int i = 1; i <= n; ++i){
    if(!viz[i]){
      ++res;
      viz[i] = 1;
      dfs(i);
    }
  }
  fout << res;
  return 0;
}