Cod sursa(job #3212510)

Utilizator AlexMoto2006Motoasca Alexandru-Lucian AlexMoto2006 Data 11 martie 2024 20:36:03
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
// ConsoleApplication2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream cin("bfs.in");
ofstream cout("bfs.out");
queue<int> q;
vector<int> mat[100005];
int sol[100005];
int n, m, start;

void bfs(int nod)
{
	for (int i = 0; i < mat[nod].size(); i++)
	{
		if (sol[mat[nod][i]] == -1)
		{
			sol[mat[nod][i]] = sol[nod] + 1;
			q.push(mat[nod][i]);
		}
	}
	q.pop();
}

int main() {
    cin >> n >> m >> start;
    for (int i = 1; i <= m; i++)
    {
		int x, y;
		cin >> x >> y;
		mat[x].push_back(y);
	}
	fill(sol, sol + n + 1, -1);
	sol[start] = 0;
	q.push(start);
	while (q.empty()==0)
	{
		bfs(q.front());
	}
	for(int i=1; i<=n; i++)
		cout<< sol[i] << " ";
    return 0;
}