Cod sursa(job #3251898)

Utilizator TonyyAntonie Danoiu Tonyy Data 27 octombrie 2024 17:48:29
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int Max = 1e5 + 1;
const int Inf = 1 << 30;

vector<int> graph[Max], d(Max, Inf);

void bfs(int node)
{
    queue<int> q;
    q.push(node);
    d[node] = 0;
    while(!q.empty())
    {
        node = q.front();
        q.pop();
        for(int i: graph[node])
        {
            if(d[node] + 1 < d[i])
            {
                d[i] = d[node] + 1;
                q.push(i);
            }
        }
    }
}

int main()
{
    int n, m, s;
    fin >> n >> m >> s;
    for(int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }
    bfs(s);
    for(int i = 1; i <= n; ++i)
        if(d[i] != Inf)
            fout << d[i] << " ";
        else
            fout << "-1 ";
    
    fin.close();
    fout.close();
    return 0;
}