Cod sursa(job #2121888)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 4 februarie 2018 14:05:17
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream in("bfs.in");
ofstream out("bfs.out");

const int MAXN = 1e5;

vector <int>g[MAXN + 1];
vector <bool>viz;
vector <int>s;

void bfs(int start){
  viz.resize(MAXN + 1, false);
  s.resize(MAXN + 1, - 1);
  queue <int>nodes;

  nodes.push(start);
  s[start] = 0;

  while (nodes.size()){
    int current;
    current = nodes.front();
    nodes.pop();
    viz[current] = true;


    for (auto x : g[current])
      if (!viz[x]){
        nodes.push(x);
        s[x] = s[current] + 1;
      }
  }
}

int n, m;

int main(){
  int start;
  in >> n >> m >> start;

  for (int i = 1; i <= m; ++ i){
    int a, b;
    in >> a >> b;
    g[a].push_back(b);
  }

  bfs(start);

  for (int i = 1; i <= n; ++ i)
    out << s[i] << " ";

  return 0;
}