Cod sursa(job #2802240)

Utilizator mediocrekarmaChirvasa George Matei mediocrekarma Data 17 noiembrie 2021 20:38:31
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

const int N_MAX = 1e5;
bool v[N_MAX + 1][N_MAX + 1];
void BFS(int start, int n) {
    int dist[N_MAX + 1] = {0};
    dist[start] = 1;
    queue<int> q;
    q.push(start);
    while (!q.empty()) {
        for (int i = 1; i <= n; ++i) {
            if (v[q.front()][i] && !dist[i]) {
                dist[i] = dist[q.front()] + 1;
                q.push(i);
            }
        }
        q.pop();
    }
    for (int i = 1; i <= n; ++i) {
        if (dist[i]) {
            cout << dist[i] - 1;
        } else {
            fout << -1;
        }
        fout << ' ';
    }

}

int main() {
    fin.tie(0);
    std::ios_base::sync_with_stdio(0);
    int n, m, s;
    fin >> n >> m >> s;
    while (m--) {
        int x, y;
        fin >> x >> y;
        v[x][y] = 1;
    }
    BFS(s, n, v);
}