Cod sursa(job #3168377)

Utilizator Dragu_AndiDragu Andrei Dragu_Andi Data 12 noiembrie 2023 12:23:22
Problema BFS - Parcurgere in latime Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

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

const int nmax=1e5 +1;

int main()
{
    vector<int> G[nmax];
    int dist[nmax];
    fill(dist, dist+nmax, nmax*10);
    int n, m, s;
    fin >> n >> m >> s;
    for(int i=1; i<=m; i++)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    queue<int> bfs;
    bfs.push(s);
    dist[s]=0;
    while(!bfs.empty())
    {
        for(auto a: G[bfs.front()])
            if(dist[bfs.front()]+1<dist[a])
            {
                dist[a]=dist[bfs.front()]+1;
                bfs.push(a);
            }
        bfs.pop();
    }
    for(int i=1; i<=n; i++)
    {
        if(dist[i]==nmax) fout << -1;
        else fout << dist[i] << ' ';
    }
    return 0;
}