Cod sursa(job #3377583)

Utilizator AndreiEnacheTheGoatAndrei Iancu Enache AndreiEnacheTheGoat Data 23 noiembrie 2026 17:31:48
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<vector<int>> edges;
vector<int> dist;

void bfs(int nod)
{
   dist[nod] = 0;
   queue<int> q;
   q.push(nod);
   int i;
   while(!q.empty())
   {
      int temp = q.front();
      q.pop();
      for(i = 0; i < edges[temp].size(); i ++)
      {
         if(dist[edges[temp][i]] == -1)
         {
            q.push(edges[temp][i]);
            dist[edges[temp][i]] = dist[temp] + 1;
         }
      }
   }
}

int main()
{
   int n, m, s, i, a, b;
   fin >> n >> m >> s;
   edges.resize(n + 1);
   for(i = 1; i <= m; i ++)
   {
      fin >> a >> b;
      edges[a].push_back(b);
   }
   dist.resize(n + 1, -1);
   bfs(s);
   for(i = 1; i <= n; i ++)
      fout << dist[i] << "\n";
   return 0;
}