Cod sursa(job #3359796)

Utilizator nistor_dora_valentinaNistor Dora Valentina nistor_dora_valentina Data 4 iulie 2026 11:59:59
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <fstream>
#include <bits/stdc++.h>

using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s, i, j, x, y, dist[100005];
vector <int> v[100005];
bool viz[100005];
queue <int> q;
int main()
{
    fin>>n>>m>>s;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y;
        v[x].push_back(y);
    }
    q.push(s);
    for(i=1; i<=n; i++)
        dist[i]=1e9;
    dist[s]=0;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto i: v[x])
            if(dist[i]==1e9)
        {
            dist[i]=dist[x]+1;
            q.push(i);
        }
    }
    for(i=1; i<=n; i++)
    if(dist[i]!=1e9)
        fout<<dist[i]<<" ";
    else
        fout<<-1<<" ";
    return 0;
}