Cod sursa(job #2121894)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 4 februarie 2018 14:09:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 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;
  viz[start] = true;

  while (nodes.size()){
    int current;
    current = nodes.front();
    nodes.pop();


    for (auto x : g[current])
      if (!viz[x]){
        nodes.push(x);
        viz[x] = true;
        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;
}