Cod sursa(job #2596426)

Utilizator avtobusAvtobus avtobus Data 9 aprilie 2020 18:33:55
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <stdio.h>
#include <bits/stdc++.h>

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

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f;

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

const int Nmax = 100555;
vi G[Nmax];
int d[Nmax];

int main(void) {
  int N, M, S;
  fin >> N >> M >> S;
  --S;
  rep(i, N) { d[i] = -1; }

  int a,b;
  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 << endl;

  return 0;
}