Cod sursa(job #2719086)

Utilizator AlexZeuVasile Alexandru AlexZeu Data 9 martie 2021 16:08:32
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

int n, m, s, dist[100010];
vector<int> edges[100010];
queue<int> q;

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

void bfs() {
    while(!q.empty()) {
        int node = q.front();
        q.pop();
        for (int i = 0; i < edges[node].size(); ++i) {
            if (dist[edges[node][i]] == -1) {
                dist[edges[node][i]] = dist[node] + 1;
                q.push(edges[node][i]);
            }
        }
    }
}

int main() {
    fin.tie(0);
    ios::sync_with_stdio(0);
    fin >> n >> m >> s;
    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        edges[x].push_back(y);
    }
    for (int i = 1; i <= n; ++i) {
        dist[i] = -1;
    }
    dist[s] = 0;
    q.push(s);
    bfs();
    for (int i = 1; i <= n; ++i) {
        fout << dist[i] << " ";
    }
	return 0;
}