Cod sursa(job #2600268)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 12 aprilie 2020 13:11:22
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.71 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m;
vector <int> edge[100005];
queue <int> q;
int dist[100005];

void BFS()
{
	int nod;
	while (!q.empty())
	{
		nod = q.front();
		q.pop();
		for(auto i : edge[nod])
			if (dist[i] == -1)
			{
				dist[i] = dist[nod] + 1;
				q.push(i);
			}
	}
}

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

	for (int i = 1; i <= n; i++)
		dist[i] = -1;
	dist[nodst] = 0;
	q.push(nodst);
	BFS();
	for (int i = 1; i <= n; i++)
		fout << dist[i] << " ";
	fin.close();
	fout.close();
	return 0;
}