Cod sursa(job #3284727)

Utilizator crina2120Arnautu Cristina-Crina crina2120 Data 12 martie 2025 09:36:35
Problema BFS - Parcurgere in latime Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
#define oo 2000000000
using namespace std;

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

int n, m, d[100003];
set <int> g[100003];
queue <int> q;

void BFS(int x)
{
    int i;
    for (i = 1; i <= n; i++)
        d[i] = oo;
    q.push(x);
    d[x] = 0;
    while (!q.empty())
    {
        i = q.front();
        q.pop();
        for (int j : g[i])
            if (d[j] > d[i] + 1)
            {
                d[j] = d[i] + 1;
                q.push(j);
            }
    }
}

int main()
{
    int i, x, y, s;
    fin >> n >> m >> s;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y;
        g[x].insert(y);
    }
    BFS(s);
    for (i = 1; i <= n; i++)
        if (d[i] == oo) fout << "-1 ";
        else fout << d[i] << " ";
    fout << "\n";
    return 0;
}
//0 1 3 4 5 7 8 9 10 11 12 13 14 15 16 17 18 21 22 24 25 26 27 29 30 34 35 36 42 44 45 47 48 51 54 56 57 58