Cod sursa(job #2884475)

Utilizator hobbitczxdumnezEU hobbitczx Data 3 aprilie 2022 19:22:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <bits/stdc++.h>
#define ll long long
#define INF 0x3F3F3F3F
using namespace std;

const string fisier = "bfs";

ifstream fin (fisier + ".in");
ofstream fout (fisier + ".out");

const int N_MAX = 1e5 + 5;

vector<int>g[N_MAX];
int n , m , p;
int d[N_MAX];

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

int main(){
    ios_base::sync_with_stdio(false);
    fin >> n >> m >> p;
    for (int i=1; i<=m; i++){
        int x , y; fin >> x >> y;
        g[x].push_back(y);
    }
    bfs(p);
    for (int i=1; i<=n; i++){
        fout << ((d[i] == 0) ? -1 : d[i] - 1) << " ";
    }
}