Cod sursa(job #3296185)

Utilizator iordacheMatei Iordache iordache Data 12 mai 2025 09:33:05
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <bits/stdc++.h>
#define pb push_back
#define int long long
using namespace std;
const int N=1e5+5;
vector<int> g[N];
bool vis[N];
int q[N];
int dep[N];
signed main()
{
    ifstream cin("bfs.in");ofstream cout("bfs.out");
    int n,m,root;
    cin>>n>>m>>root;
    for(int _=1;_<=m;++_)
    {
        int u,v;cin>>u>>v;
        g[u].pb(v);
    }
    q[1]=root;
    int it=1,sz=1;
    for(int i=1;i<=n;++i) dep[i]=-1;
    dep[root]=0;
    while(it<=sz)
    {
        int u=q[it];
        ++it;
        vis[u]=1;
        for(auto v:g[u])
        {
            if(vis[v]) continue;
            dep[v]=dep[u]+1;
            ++sz;
            q[sz]=v;
        }
    }
    for(int i=1;i<=n;++i) cout<<dep[i]<<" ";
}