Cod sursa(job #2857715)

Utilizator vladp1324Vlad Pasare vladp1324 Data 26 februarie 2022 10:31:58
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 0.83 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];
bool ver[100001];

void bfs (int nc) {
  for (int i = 1; i <= n; i++)
    d[i] = -1;
  d[nc] = 0;
  q.push (nc);
  ver[nc] = true;
  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 ver[nv]) {
        q.push (nv);
        d[nv] = d[nc] + 1;
      }
    }
  }
}

int main()
{
  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] << ' ';
  return 0;
}