Cod sursa(job #3213696)

Utilizator tomaionutIDorando tomaionut Data 13 martie 2024 12:55:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>
#define INF 2e9
using namespace std;

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

int n, m, S, dp[100005];
vector <int> a[100005];
queue <int> Q;
int main()
{
    int i, x, y;
    fin >> n >> m >> S;
    for (i = 1; i <= m; i++)
    {
        fin >> x >> y;
        a[x].push_back(y);
    }

    for (i = 1; i <= n; i++)
        dp[i] = INF;
    dp[S] = 0;
    Q.push(S);
    while (!Q.empty())
    {
        x = Q.front();
        Q.pop();
        for (auto w : a[x])
            if (dp[w] == INF)
            {
                dp[w] = dp[x] + 1;
                Q.push(w);
            }
    }
    for (int i = 1; i <= n; i++)
        if (dp[i] == INF)
        fout << "-1 ";
    else fout << dp[i] << " ";

    return 0;
}