Cod sursa(job #2869677)

Utilizator Sebi_MafteiMaftei Sebastioan Sebi_Maftei Data 11 martie 2022 19:09:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
#define MOD 1999999973

using namespace std;

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

int n, m, st, d[100003];
vector<int> h[100003];

void Citire()
{
    int x, y;
    fin >> n >> m >> st;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        h[x].push_back(y);
    }
}

void BFS(int k)
{
    int nod;
    queue<int> q;
    q.push(k);

    for (int i = 1; i <= n; i++)
        d[i] = 1e9;
    d[k] = 0;

    while(!q.empty())
    {
        nod = q.front();
        q.pop();
        for (int w : h[nod])
        {
            if(d[w] > d[nod] + 1)
            {
                d[w] = 1 + d[nod];
                q.push(w);
            }
        }
    }
    for (int i = 1; i <= n; i++)
        if (d[i] == 1e9) fout << "-1 ";
        else fout << d[i] << " ";
}

int main()
{
    Citire();
    BFS(st);
    return 0;
}