Cod sursa(job #2609530)

Utilizator ionutomutiuIonut Tomutiu ionutomutiu Data 2 mai 2020 20:19:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
vector <int> adjacent[100005];
int visited[100005];
int N, M, S;
int ans[100005];
void bfs ()
{
    queue <pair <int, int >> neighbors;
    neighbors.push ({S, 0});
    visited[S] = 1;
    while (!neighbors.empty ())
    {
        int curr_node = neighbors.front ().first;
        int length = neighbors.front ().second;
        ans[curr_node] = length;
        for (int i : adjacent[curr_node])
            if (!visited[i])
            {
                visited[i] = 1;
                neighbors.push ({i, length + 1});
            }
        neighbors.pop ();
    }
}
int main ()
{
    fin >> N >> M >> S;
    for (int i = 1; i <= M; i++)
    {
        int x, y;
        fin >> x >> y;
        adjacent[x].push_back (y);
    }
    fill (ans + 1, ans + N + 1, -1);
    bfs ();
    for (int i = 1; i <= N; i++)
        fout << ans[i] << " ";
    return 0;
}