Cod sursa(job #2003200)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 22 iulie 2017 11:53:13
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include <cstdio>
#include <vector>

using namespace std;

int const nmax = 100000;

FILE *in, *out;

int n, m, nc;
vector <int> g[1 + nmax];
int cc[1 + nmax];  //numarul componentei conex din care face parte nodul i

void dfs(int from) {
  for(int i=0; i < g[from].size(); i++) {
    if(cc[g[from][i]] == 0) {
      cc[g[from][i]] = nc;
      dfs(g[from][i]);
    }
  }
}

int main() {
  in = fopen("dfs.in", "r");
  out = fopen("dfs.out", "w");
  fscanf(in, "%d %d", &n, &m);
  for(int i = 1; i <= m; i ++) {
    int to,from;
    fscanf(in, "%d %d", &from, &to);
    g[to].push_back(from);
    g[from].push_back(to);
  }

  for(int i=1; i<=n; i++) {
    if(cc[i] == 0) {
      nc++;
      cc[i] = nc;
      dfs(i);
    }
  }
  fprintf(out, "%d\n", nc);
  return 0;
}