Cod sursa(job #2745175)

Utilizator djanaDiana Simion djana Data 25 aprilie 2021 22:56:06
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;

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

static constexpr int NMAX = 100500;
int n, m, s;
vector<int> adj[NMAX];

queue<int> q;
vector<int> d(NMAX);

void read() {
    fin >> n >> m >> s;
    for (int i = 1, x, y; i <= m; i++) {
        fin >> x >> y;
        adj[x].push_back(y);
    }
}

void bfs() {
    for (int i = 1; i <= n; i++) {
        d[i] = INT32_MAX;
    }

    d[s] = 0;
    q.push(s);

    while(!q.empty()) {
        int node = q.front();
        q.pop();

        for (auto neigh : adj[node]) {
            if (d[node] + 1 < d[neigh]) {
                d[neigh] = d[node] + 1;
                q.push(neigh);
            } 
        }
    }
}

void print_result() {
    for (int i = 1; i <= n; i++) {
        if (d[i] == INT32_MAX) {
            d[i] = -1;
        }
        
        fout << d[i] << " ";
    }
    fout << endl;
}

int main() {
    read();
    bfs();
    print_result();
    return 0;
}