Cod sursa(job #3369823)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 22 octombrie 2026 10:47:10
Problema BFS - Parcurgere in latime Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

const std::string fileName = "bfs";
const int N = 1e5 + 1;
const int INFINIT = 1e6 + 10;

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

std::vector<int> graph[N];
int n, sourceNode;

int BFS(int startNode, int finalNode)
{
	std::vector<int> dist(n + 1, INFINIT);
	std::queue<int> q;
	q.push(startNode);
	dist[startNode] = 0;

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

		for (const auto& neighbour : graph[node])
		{
			if (dist[neighbour] > dist[node] + 1)
			{
				dist[neighbour] = dist[node] + 1;
				q.push(neighbour);
			}
		}
	}

	return dist[finalNode];
}

int main()
{
	int m;
	fin >> n >> m >> sourceNode;
	for (int i = 1; i <= m; ++i)
	{
		int x, y;
		fin >> x >> y;
		graph[x].push_back(y);
	}

	for (int i = 1; i <= n; ++i)
	{
		int d = BFS(sourceNode, i);
		fout << (d != INFINIT ? d : -1) << ' ';
	}

	return 0;
}