Cod sursa(job #2748590)

Utilizator muiepulicimatacutactu muiepulici Data 1 mai 2021 18:43:25
Problema BFS - Parcurgere in latime Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>

int N;
std::vector<int> G[100001];

int st[100000];
int viz[100001];

int cost[100001];

void bfs(int k) {
	viz[k] = 1;
	st[0] = k;

	int i = 0;
	int j = 0;
	int curr;

	while (i <= j) {
		curr = st[i];

		for (auto& nod : G[curr]) {
			if (viz[nod] == 0) {
				viz[nod] = 1;
				st[++j] = nod;
				cost[nod] = cost[curr] + 1;
			}
		}

		++i;
	}

}

int main() {
	std::ifstream fin("bfs.in");
	std::ofstream fout("bfs.out");

	int M, S;
	fin >> N >> M >> S;

	int x, y;

	for (int i = 0; i < M; ++i) {
		fin >> x >> y;

		G[x].push_back(y);
	}

	fin.close();

	memset(cost, -1, sizeof(cost));
	cost[S] = 0;

	bfs(S);

	for (int i = 1; i <= N; ++i) {
		fout << cost[i] << ' ';
	}
	fout << '\n';

	fout.close();

	return 0;
}