Cod sursa(job #2862686)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 5 martie 2022 18:24:15
Problema BFS - Parcurgere in latime Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x <<": " << x << "\n";
using ll = long long;

const string myf = "bfs";
ifstream fin(myf + ".in");
ofstream fout(myf + ".out");

const  int mod = 1999999973;

int n, m, src;
int d[100005];
vector<int> g[100005];
queue<int> q;
void bfs(int src) {
	for (int i = 1; i <= n; ++i)
		d[i] = 2e9;
	d[src] = 0;
	q.push(src);
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		for (auto i : g[x]) {
			if (d[i] > d[x] + 1) {
				d[i] = d[x] + 1;
				q.push(i);
			}
		}
	}
}

int main() {
	int x, y;
	fin >> n >> m >> src;
	while (m--) {
		fin >> x >> y;
		g[x].pb(y);
	}

	bfs(src);
	for (int i = 1; i <= n; ++i)
		if (d[i] == 2e9)
			fout << "-1 ";
		else fout << d[i] << " ";
	fin.close();
	fout.close();
	return 0;
}