Cod sursa(job #3375180)

Utilizator dimitrie_gheorgheGheorghe Dimitrie dimitrie_gheorghe Data 10 noiembrie 2026 20:56:26
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("bfs.in");
ofstream g("bfs.out");

int n, m, k, x, y;
vector<int> dist;
vector<vector<int>> graph;

void bfs(int node)
{
	queue<int> q;
	q.push(node);
	dist[node] = 0;

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

		for(int next: graph[node])
		{
			if(dist[next] == -1)
			{
				dist[next] = dist[node] + 1;
				q.push(next);
			}
		}
	}
}

int main()
{
	f >> n >> m >> k;
	dist.assign(n + 1, -1);
	graph.assign(n + 1, vector<int>());

	for(int i = 1; i <= m; i++)
	{
		f >> x >> y;
		graph[x].push_back(y);
	}

	bfs(k);

	for(int i = 1; i <= n; i++)
	{
		g << dist[i] << ' ';
	}

	return 0;
}