Cod sursa(job #3314242)

Utilizator Latyn76Tinica Alexandru Stefan Latyn76 Data 9 octombrie 2025 08:25:10
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

vector<int> a[100005];
int cost[100005];

void bfs(int nod)
{
    queue<int> q;
    q.push(nod);
    cost[nod] = 0;
    while (!q.empty())
    {
        int actNod = q.front();
        q.pop();
        for (auto next : a[actNod])
            if (cost[next] > cost[actNod] + 1)
            {
                cost[next] = cost[actNod] + 1;
                q.push(next);
            }
    }
}

int main()
{
    int n, m, s;
    ifstream fin("bfs.in");
    ofstream fout("bfs.out");
    fin >> n >> m >> s;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        a[x].push_back(y);
    }
    for (int i = 0; i <= 100000; i++)
        cost[i] = 1e9;
    bfs(s);
    for (int i = 1; i <= n; i++)
        fout << ((cost[i] == 1e9) ? -1 : cost[i]) << ' ';
    fout << '\n';
    return 0;
}