Cod sursa(job #3289887)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 28 martie 2025 23:50:45
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e5;

vector<int> g[MAXN + 2];
int d[MAXN + 2];

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

    while (!nodes.empty())
    {
        cur = nodes.front();
        nodes.pop();

        for (auto &x : g[cur])
            if (x != s && d[x] == 0)
            {
                nodes.push(x);
                d[x] = d[cur] + 1;
            }
    }
}

int main()
{
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);

    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);

    int n, m, s;
    cin >> n >> m >> s;

    // vector<vector<int>> g(n + 2);
    // vector<int> d(n + 2, 0);

    for (int i = 0; i < m; ++i)
    {
        int a, b;
        cin >> a >> b;
        g[a].push_back(b);
    }

    bfs(s);

    for (int i = 1; i <= n; ++i)
        if (d[i] == 0 && i != s)
            cout << -1 << ' ';
        else
            cout << d[i] << ' ';
    cout << '\n';

    return 0;
}