Cod sursa(job #3214854)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 14 martie 2024 15:10:07
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>

using namespace std;

const int max_size = 1e5 + 20;

int d[max_size];
vector <int> mc[max_size];
queue <int> q;

void bfs (int src)
{
    q.push(src);
    d[src] = 1;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        for (auto f : mc[nod])
        {
            if (d[f] == 0)
            {
                d[f] = d[nod] + 1;
                q.push(f);
            }
        }
    }
}

void solve ()
{
    int n, m, src;
    cin >> n >> m >> src;
    while (m--)
    {
        int x, y;
        cin >> x >> y;
        mc[x].push_back(y);
    }
    bfs(src);
    for (int i = 1; i <= n; i++)
    {
        cout << d[i] - 1 << " ";
    }
    cout << '\n';
}

signed main ()
{
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#else
    freopen("bfs.in", "r", stdin);
    freopen("bfs.out", "w", stdout);
#endif // LOCAL
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    long long tt;
    //cin >> tt;
    tt = 1;
    while (tt--)
    {
        solve();
    }
    return 0;
}