Cod sursa(job #2976632)

Utilizator the_horoHorodniceanu Andrei the_horo Data 9 februarie 2023 19:39:18
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <array>
#include <fstream>
#include <queue>
#include <vector>

std::array<std::vector<int>, 100010> edges;

std::vector<int> bfs (int start, int n) {
	std::queue<int> q;
	std::vector<int> result(n + 1, -1);

	result[start] = 0;
	q.emplace(start);

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

		for (auto to: edges[node])
			if (result[to] == -1) {
				result[to] = result[node] + 1;
				q.emplace(to);
			}
	}

	return result;
}

int main () {
	std::ifstream in("bfs.in");
	in.exceptions(in.failbit);
	std::ofstream out("bfs.out");
	out.exceptions(out.failbit);

	int n, m, s;
	in >> n >> m >> s;

	for (int i = 0; i < m; ++ i) {
		int x, y;
		in >> x >> y;

		edges[x].emplace_back(y);
	}

	const auto result = bfs(s, n);
	
	for (int i = 1; i <= n; ++ i)
		out << result[i] << ' ';
	out << '\n';
}