Cod sursa(job #2195720)

Utilizator WebDesignbyTMGhiorghiu Ioan-Viorel WebDesignbyTM Data 17 aprilie 2018 11:22:20
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.69 kb
#define inf 0x3f3f3f3f
#define DM 100001
#include <cstring>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

ifstream fi ("bfs.in");
ofstream fo ("bfs.out");
int n, m, s, a, b, dst[DM];
queue <int> q;
vector <int> v[DM];

void bfs()
{
	q.push(s);
	while (!q.empty())
	{
		a = q.front();
		b = dst[a];
		q.pop();
		for (auto i:v[a])
			if (dst[i] > b + 1)
			{
				dst[i] = b + 1;
				q.push(i);
			}
	}
}

int main()
{
	fi >> n >> m >> s;
	memset(dst, inf, sizeof(dst));
	for (int i = 1; i <= m; ++i)
	{
		fi >> a >> b;
		v[a].push_back(b);
	}
	dst[s] = 0;
	bfs();
	for (int i = 1; i <= n; ++i)
		if (dst[i] == inf)
			fo << -1 << ' ';
		else
			fo << dst[i] << ' ';
	return 0;
}