Cod sursa(job #2461755)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 26 septembrie 2019 09:26:08
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>
#define maxi 100003
using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

vector <int> vec[maxi];
queue <int> coada;
int cost[maxi];


void bfs(int s)
{
    coada.push(s);
    cost[s] = 0;
    while (!coada.empty())
    {
        int nod = coada.front();
        coada.pop();
        for (auto next : vec[nod])
            if (cost[next] == 0 && next != s)
            {
                cost[next] = cost[nod] + 1;
                coada.push(next);
            }
    }
}

int main()
{
  int n, m, s;
  f >> n >> m >> s;
  while (m --)
  {
      int x, y;
      f >> x >>y;
      vec[x].push_back(y);
  }
  bfs(s);
  for (int nod = 1; nod <= n; ++ nod)
      if (cost[nod] == 0 && nod != s)
          g << -1 << " ";
      else
          g << cost[nod] << " ";
}