Cod sursa(job #2211724)

Utilizator PetyAlexandru Peticaru Pety Data 11 iunie 2018 15:45:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.71 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<int>v[100002];
int n, m, x, y, nr, viz[100002], s, d[100002];

void BFS() {
  queue<int>q;
  q.push(s);
  viz[s] = 1;
  while (!q.empty()) {
    int x = q.front();
    q.pop();
    for (int i = 0; i < v[x].size(); i++) {
      int blah = v[x][i];
      if (!viz[blah]) {viz[blah] = 1; d[blah] = d[x] + 1; q.push(blah);}
    }
  }
}

int main()
{
  fin >> n >> m >> s;
  for (int i = 1; i <= m; i++) {
    fin >> x >> y;
    v[x].push_back(y);
  }
  for (int i = 1; i <= n; i++)d[i] = -1;
  d[s] = 0;
  BFS();
  for (int i = 1; i <= n; i++)
    fout << d[i] << " ";
  return 0;
}