Cod sursa(job #3239882)

Utilizator ChopinFLazar Alexandru ChopinF Data 8 august 2024 15:30:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>
using namespace std;
std::string file = "bfs";
std::ifstream fin(file + ".in");
std::ofstream fout(file + ".out");
// #define fin std::cin
// #define fout std::cout
int n, m;
std::vector<std::vector<int>> gf;
std::vector<int> dist;
void bfs(int start) {
  std::queue<int> q;
  q.push(start);
  dist[start] = 0;
  while (!q.empty()) {
    int current = q.front();
    q.pop();
    for (const auto &nextNode : gf[current]) {
      if (dist[nextNode] == -1) {
        dist[nextNode] = dist[current] + 1;
        q.push(nextNode);
      }
    }
  }
}
int32_t main(int32_t argc, char *argv[]) {
  ios_base::sync_with_stdio(false);
  fin.tie(0);
  fout.tie(0);
  int x;
  fin >> n >> m >> x;
  gf.resize(n + 1);
  dist.resize(n + 1, -1);
  for (int i = 0; i < m; ++i) {
    int a, b;
    fin >> a >> b;
    gf[a].push_back(b);
  }
  bfs(x);
  for (int i = 1; i <= n; ++i) {
    fout << dist[i] << " ";
  }
  fout << "\n";
  return 0;
}