Cod sursa(job #2214288)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 18 iunie 2018 18:28:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int MAXN = 1e5;
const int MAXM = 1e6;

int n, m, s;
vector <int>g[MAXN + 1];
int d[MAXN + 1];

void bfs(int start) {
	queue <int>nodes;
	bool viz[MAXN + 1];
	for (int i = 1; i <= n; ++ i)
		viz[i] = 0;
	nodes.push(start);
	viz[start] = 1;

	while (nodes.size()) {
		int cur = nodes.front();
		nodes.pop();

		for (auto x : g[cur]) {
			if (!viz[x]) {
				viz[x] = 1;
				d[x] = d[cur] + 1;
				nodes.push(x);
			}
		}
	}
}

int main() {
	in >> n >> m >> s;

	for (int i = 1; i <= m; ++ i) {
		int a, b;
		in >> a >> b;
		g[a].push_back(b);
	}

	bfs(s);

	for (int i = 1; i <= n; ++ i) {
	  if (d[i] == 0 && i != s)
      out << -1 << ' ';
    else
      out << d[i] << ' ';
	}


	return 0;
}