Cod sursa(job #2726661)

Utilizator avtobusAvtobus avtobus Data 21 martie 2021 10:55:02
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <stdio.h>
#include <bits/stdc++.h>

#define rep(i, n) for(int i = 0; i < (int)(n); i++)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;

ifstream fin {"bfs.in"};
ofstream fout {"bfs.out"};
const int Nmax = 100'005;
vi G[Nmax];
int d[Nmax];

int main(void) {
  // freopen("bfs.in", "r", stdin);
  std::ios_base::sync_with_stdio(false);
  std::cin.tie(NULL);

  memset(d, -1, sizeof(d));
  int N, M, S,a,b;
  fin >> N >> M >> S;
  --S;
  rep(i, M) {
    fin >> a >> b;
    --a; --b;
    G[a].push_back(b);
  }
  queue<int> Q;
  Q.push(S); d[S] = 0;
  while(!Q.empty()) {
    int x = Q.front(); Q.pop();
    for(auto y: G[x]) {
      if (d[y] != -1)
        continue;
      d[y] = d[x] + 1;
      Q.push(y);
    }
  }

  rep(i, N) {
    fout << d[i] << ' ';
  }
  fout << '\n';

  return 0;
}