Cod sursa(job #2487587)

Utilizator MithrilBratu Andrei Mithril Data 4 noiembrie 2019 23:00:10
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <bits/stdc++.h>

#define NMAX 100001

using namespace std;

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

int dist[NMAX];
vector<int> graph[NMAX];
queue<int> q;

int main()
{
  int n,m,s;
  fin >> n >> m >> s;
  while(m--)
  {
    int x, y;
    fin >> x >> y;
    graph[x].push_back(y);
  }
  for(int i = 1; i <= n; i++) dist[i] = -1;
  q.push(s);
  dist[s] = 0;
  while(!q.empty())
  {
    int node = q.front();
    q.pop();
    for(auto x : graph[node])
    {
      if(dist[x] == -1)
      {
        dist[x] = dist[node]+1;
        q.push(x);
      }
    }
  }

  for(int i = 1; i <= n; i++) fout << dist[i] << ' ';
  fin.close();
  fout.close();

  return 0;
}