Cod sursa(job #2399110)

Utilizator robertstrecheStreche Robert robertstreche Data 6 aprilie 2019 21:40:38
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>

#define NMAX 100005

using namespace std;

vector <int> edges[NMAX];

bool ap[NMAX];
int min_dist[NMAX];

void bfs(int source) {
	queue <int> nodes;

	nodes.push(source);
	min_dist[source] = 0;
	ap[source] = 1;

	while (!nodes.empty()) {
		int node = nodes.front();

		nodes.pop();

		for (auto it : edges[node]) {
			if (!ap[it]) {
				ap[it] = 1;
				min_dist[it] = min_dist[node] + 1;
				nodes.push(it);
			}
		}
	}
}

int main()
{
	ifstream f("bfs.in");
	ofstream g("bfs.out");

	int n, m, source, x, y;

	f >> n >> m >> source;
	for (int i = 0; i < m; i++) {
		f >> x >> y;
		edges[x].push_back(y);
	}

	for (int i = 1; i <= n; i++)
		min_dist[i] = -1;

	bfs(source);

	for (int i = 1; i <= n; i++) {
		g << min_dist[i] << " ";
	}
}