Cod sursa(job #3178097)

Utilizator bombatongaMunteanu David Ioan bombatonga Data 30 noiembrie 2023 23:26:07
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>
#include <queue>

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

std::vector<int> vis;

std::queue<int> queue;

std::vector<std::vector<int>> graph;

void bfs(int node) {
	queue.push(node);
	vis[node] = 1;
	while (!queue.empty()) {
		node = queue.front();
		queue.pop();
		for (int i : graph[node])
			if (!vis[i]) {
				queue.push(i);
				vis[i] = vis[node]+1;
			}
	}
}

int main() {
	int N, M, S;
	fin >> N >> M >> S;
	graph.assign(N + 1, std::vector<int>());

	for (int i = 1; i <= M; i++) {
		int x, y;
		fin >> x >> y;
		graph[x].emplace_back(y);
	}

	bfs(S);

	for (int i = 1; i <= N; i++)
		if (!vis[i])
			fout << -1 << ' ';
		else
			fout << vis[i]-1 << ' ';

	graph.clear();
	fin.clear(); fout.clear();
	return 0;
}