Cod sursa(job #1206423)

Utilizator pulseOvidiu Giorgi pulse Data 9 iulie 2014 21:46:45
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <cstdio>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f

using namespace std;

int n, m, first, cost[100005];
vector <int> G[100005];

void BFS()
{
	queue <int> Q;
	for (int i = 1; i <= n; ++i)
		cost[i] = INF;
	cost[first] = 0;
	Q.push(first);
	while (!Q.empty())
	{
		int node = Q.front();
		Q.pop();
		for (vector <int> :: iterator it = G[node].begin(); it != G[node].end(); ++it)
		{
			if (cost[*it] > cost[node] + 1)
			{
				cost[*it] = cost[node] + 1;
				Q.push(*it);
			}
		}
	}
}

int main()
{
	freopen("bfs.in", "r", stdin);
	freopen("bfs.out", "w", stdout);
	scanf("%d %d %d", &n, &m, &first);
	for (int i = 1; i <= m; ++i)
	{
		int a, b;
		scanf("%d %d", &a, &b);
		G[a].push_back(b);
	}
	BFS();
	for (int i = 1; i <= n; ++i)
	{
		if (cost[i] != INF)
			printf("%d ", cost[i]);
		else
			printf("-1 ");
	}
	return 0;
}