Cod sursa(job #3296187)

Utilizator andrei.nNemtisor Andrei andrei.n Data 12 mai 2025 09:35:28
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <bits/stdc++.h>
#define int int64_t

using namespace std;

const int NMAX = 100005;

vector<int> v[NMAX];
queue<int> q;
int depth[NMAX];

void bfs(int source)
{
    q.push(source);
    depth[source] = 0;
    while(!q.empty())
    {
        int node = q.front();
        q.pop();
        for(auto &x : v[node])
            if(depth[x] == 0 && x != source)
            {
                q.push(x);
                depth[x] = depth[node] + 1;
            }
    }
}

signed main()
{
    ifstream fin ("bfs.in");
    ofstream fout ("bfs.out");
    ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
    int n,m,s; fin>>n>>m>>s;
    for(int i=0; i<m; ++i)
    {
        int x,y; fin>>x>>y;
        v[x].push_back(y);
    }
    bfs(s);
    for(int i=1; i<=n; ++i)
        fout<<(depth[i] == 0 && i != s ? -1 : depth[i])<<' ';
    return 0;
}