Cod sursa(job #412415)

Utilizator slayer4uVictor Popescu slayer4u Data 5 martie 2010 16:48:08
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector <int> x[100001];
queue <int> q, step;

long n, m, s, a, b, v[100001], rez[100001];

int main ()
{
	freopen ("bfs.in", "rt", stdin);
	freopen ("bfs.out", "wt", stdout);

	scanf("%ld %ld %ld", &n ,&m, &s);

	for (long i = 1; i <= m; ++i)
	{
		scanf("%ld %ld", &a, &b);
		x[a].push_back(b);
	}

	q.push(s);
	step.push(0);
	v[s] = 1;
	while (!q.empty())
	{
		for (long j = 0; j < x[q.front()].size(); ++j)
			if (v[x[q.front()][j]] != 1)
			{
				q.push(x[q.front()][j]);
				rez[x[q.front()][j]] = step.front() + 1;
				step.push(step.front() + 1);
				v[x[q.front()][j]] = 1;
			}
		q.pop();
		step.pop();
	}

	for (long i = 1; i <= n; ++i)
	{
		if (i == s)
			printf("0 ");
		else
		if (!rez[i])
			printf("-1 ");
		else
			printf("%ld ", rez[i]);
	}
	printf("\n");

	return 0;
}