Cod sursa(job #2117987)

Utilizator ioana_pelinIoana Pelin ioana_pelin Data 29 ianuarie 2018 21:03:23
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

int n, m, start, lg[NMAX];
vector <int> LAD[NMAX];
queue <int> coada;

void BFS();

int main()
{
	int i, x, y;

	fin >> n >> m >> start;

	for (i = 1; i <= m; i++)
	{
		fin >> x >> y;
		if (x != y)
			LAD[x].push_back(y);
	}

	BFS();

	lg[start] = -1;

	for (i = 1; i <= n; i++)
		if (lg[i] > 0)
			fout << lg[i] << ' ';
		else
			if (lg[i] == 0)
				fout << -1 << ' ';
			else
				fout << 0 << ' ';

	return 0;
}

void BFS()
{
	int i, x;

	coada.push(start);

	while (!coada.empty())
	{
		x = coada.front(); coada.pop();
		for (i = 0; i < LAD[x].size(); i++)
			if (!lg[LAD[x][i]])
			{
				coada.push(LAD[x][i]); lg[LAD[x][i]] = lg[x] + 1;
			}
	}
}