Cod sursa(job #3369839)

Utilizator AlphxByteStefan Alexandru AlphxByte Data 22 octombrie 2026 10:50:46
Problema BFS - Parcurgere in latime Scor 100
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;
std::vector<int> dist;
int sourceNode;

void BFS(int startNode)
{
	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);
			}
		}
	}
}

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);
	}

	dist = std::vector<int>(n + 1, INFINIT);

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

	return 0;
}