Cod sursa(job #3350661)

Utilizator Alex_at_gameIustin-Alexandru Frateanu Alex_at_game Data 11 aprilie 2026 17:44:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
#define all(v) begin(v), end(v)
#define al(v, l, r) begin(v) + l, begin(v) + r + 1
#define sz(v) (int)v.size()
#define pb push_back
#define pob pop_back
#define fs first
#define sd second

constexpr int inf = 2e9;
constexpr ll infll = 4e18;
constexpr int N = 1e5 + 5;

int n, m, s, d[N];
vector<int> g[N];

void bfs() {
    queue<int> q;
    q.push(s);

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

        for (int y : g[x]) {
            if (y == s || d[y]) {
                continue;
            }

            d[y] = d[x] + 1;
            q.push(y);
        }
    }

    for (int i = 1; i <= n; ++i) {
        if (i == s || d[i]) {
            continue;
        }

        d[i] = -1;
    }
}

signed main() {
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

    cin >> n >> m >> s;
    for (int i = 0, x, y; i < m; ++i) {
        cin >> x >> y;
        g[x].pb(y);
    }

    bfs();
    for (int i = 1; i <= n; ++i) {
        cout << d[i] << " \n"[i == n];
    }
}