Cod sursa(job #2857810)

Utilizator vladp1324Vlad Pasare vladp1324 Data 26 februarie 2022 13:21:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define ll long long
using namespace std;

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

int n, m, s, d[100001];
queue < int > q;
vector < int > v[100001];

void bfs (int nc) {
  d[nc] = 1;
  q.push (nc);
  while (not q.empty ()) {
    nc = q.front ();
    q.pop ();
    for (int i = 0; i < v[nc].size (); i++) {
      int nv = v[nc][i];
      if (not d[nv]) {
        q.push (nv);
        d[nv] = d[nc] + 1;
      }
    }
  }
}

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(NULL);

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