Cod sursa(job #3367117)

Utilizator lefterache_stefanLefterache Stefan lefterache_stefan Data 6 octombrie 2026 10:55:43
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXIM = 100001;
vector<int> graf[MAXIM];

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

int dist[MAXIM];

static inline void bfs(int start) {
	queue<int> q;
	dist[start] = 0;
	q.push(start);
	while (!q.empty()) {
		const int current = q.front();
		q.pop();
		for (const auto& vecin : graf[current]) {
			if (dist[vecin] != -1) {
				continue;
			}
			dist[vecin] = dist[current] + 1;
			q.push(vecin);
		}
	}
}

int main() {
	int start, n, m;
	fin >> n >> m >> start;

	for (int i = 0; i < m; i++) {
		int x, y;
		fin >> x >> y;
		graf[x].push_back(y);
	}
	fill(dist, dist + MAXIM, -1);
	bfs(start);
	for (int i = 1; i <= n; i++) {
		fout << dist[i] << ' ';
	}
}