Cod sursa(job #2168205)

Utilizator Alex_AmarandeiAmarandei Matei Alexandru Alex_Amarandei Data 14 martie 2018 10:02:19
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");

struct node
{
	int x;
	node* next;
};

typedef node* LSI;

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

void BFS();
void insert(LSI& l, int x);

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

	fin >> n >> m >> start;

	for (i = 1; i <= m; i++)
	{
		fin >> x >> y;
		if (x != y)
			insert(LAD[x], 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 x;
	node* p;

	coada.push(start);

	while (!coada.empty())
	{
		x = coada.front(); coada.pop();
		for (p = LAD[x]; p; p = p->next)
			if (!lg[p->x])
			{
				coada.push(p->x); lg[p->x] = lg[x] + 1;
			}
	}
}

void insert(LSI& l, int x)
{
	node* p = new node;
	p->x = x;
	p->next = l;
	l = p;
}