Cod sursa(job #3375148)

Utilizator dragosdragonnIosub Dragos Casian dragosdragonn Data 10 noiembrie 2026 17:28:25
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

using namespace std;

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

vector<int> G[100001];
int d[100001];
const int INF = 1e9;

int n; 

void bfs(int sursa)
{
    for(int i = 1; i <= n; i++)
    {
        d[i] = INF;
    }

    d[sursa] = 0; 

    queue<int> q; 
    q.push(sursa);

    while(!q.empty())
    {
        int nod = q.front();
        q.pop();

        for(auto vec : G[nod])
        {
            if(d[vec] > d[nod] + 1)
            {
                d[vec] = d[nod] + 1;
                q.push(vec);
            }
        }
    }
}
int main()
{
    int m, s;
    fin >> n >> m >> s;
    for(int i = 0; i < m; i++)
    {
        int x, y;
        fin >> x >> y; 
        G[x].push_back(y);
    }

    bfs(s);

    for(int i = 1; i <= n; i++)
    {
        if(d[i] == INF)
        {
            fout << -1 << ' ' ;
        }
        else 
            fout << d[i] << ' ';
    }
    return 0;
}