Cod sursa(job #2383951)

Utilizator raul044Moldovan Raul raul044 Data 19 martie 2019 21:56:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define MAXN 100001

using namespace std;

ifstream fin("bfs.in");
ofstream fout("bfs.out");

int n, m, nod;
vector <int> G[MAXN];

void citire () {
	fin >> n >> m >> nod;
	for (int i = 0; i < m; ++i) {
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
	}
}

void bfs (int nod) {
	queue <int> Q;
	int V[MAXN] = {0}, Dist[MAXN] = {0};
	Dist[nod] = 0;
	V[nod]++;
	Q.push(nod);
	while (!Q.empty()) {
		int x = Q.front();
		Q.pop();
		int size = G[x].size();
		for (int i = 0; i < size; ++i) {
			int y = G[x][i];
			if (!V[y]) {
				Q.push(y);
				V[y]++;
				Dist[y] = Dist[x] + 1;
			}
		}
	}

	for (int i = 1; i <= n; ++i) {
		if (V[i]) {
			fout << Dist[i] << " ";
		} 
		else {
			fout << -1 << " ";
		}
	}
}

int main () {
	citire();
	bfs(nod);
}