Cod sursa(job #2003202)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 22 iulie 2017 11:58:32
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>

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]);
    }
  }
}

void bfs(int from) {
  queue <int> q;
  q.push(from);
  while(0 < q.size()) {
    int s = q.front();
    q.pop();
    for(int i = 0;i < g[s].size();i ++) {
      if(cc[g[from][i]] == 0) {
        cc[g[from][i]] = nc;
        q.push(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;
      bfs(i);
    }
  }
  fprintf(out, "%d\n", nc);
  return 0;
}