Cod sursa(job #3319323)

Utilizator EckchartZgarcea Robert-Andrei Eckchart Data 31 octombrie 2025 17:48:13
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include "bits/stdc++.h"
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pi = pair<int, int>;
using pll = pair<ll, ll>;
using pd = pair<double, double>;
using pld = pair<ld, ld>;
// #define LOCAL
#ifdef LOCAL
ifstream cin("input.txt");
ofstream cout("output2.txt");
#else
ifstream cin("bfs.in");
ofstream cout("bfs.out");
#endif
#define cin ::cin
#define cout ::cout


int main()
{
    int N, M, S;
    cin >> N >> M >> S;
    vector<vector<int>> adj(N + 1);
    while (M--)
    {
        int x, y;
        cin >> x >> y;
        adj[x].emplace_back(y);
    }

    vector<int> min_dist(N + 1, -1);
    min_dist[S] = 0;

    [&]() -> void
    {
        queue<int> nodes;
        nodes.emplace(S);
        while (!nodes.empty())
        {
            const int cnode = nodes.front();
            nodes.pop();

            for (const int anode : adj[cnode])
            {
                if (min_dist[anode] != -1)
                {
                    continue;
                }
                min_dist[anode] = min_dist[cnode] + 1;
                nodes.emplace(anode);
            }
        }
    }();

    for (int i = 1; i <= N; ++i)
    {
        cout << min_dist[i] << " ";
    }
}