Cod sursa(job #3300111)

Utilizator SimifilLavrente Simion Simifil Data 12 iunie 2025 21:07:54
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>
#include <climits>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");

int main()
{
    int n, m, s;
    f >> n >> m >> s;
    vector<int> adj[n+1];
    int ans[n+1];
    deque<int> d;
    for( int i = 1; i <= n; ++i )
    {
        ans[i] = INT_MAX;
    }
    for( int i = 1; i <= m; ++i )
    {
        int x, y;
        f >> x >> y;
        if( x != y )
            adj[x].push_back(y);
    }
    d.push_front(s);
    ans[s] = 0;
    while( d.empty() == false )
    {
        int parinte = d.back();
        d.pop_back();
        for( auto copil : adj[parinte] )
        {
            if( ans[copil] > ans[parinte] + 1 )
            {
                ans[copil] = ans[parinte] + 1;
                d.push_front( copil );
            }
        }
    }
    for( int i = 1; i <= n; ++i )
    {
        if( ans[i] == INT_MAX )
            g << "-1 ";
        else
            g << ans[i] << " ";
    }
	return 0;
}