Pagini recente » Cod sursa (job #1228158) | Cod sursa (job #721589) | Cod sursa (job #1393992) | Cod sursa (job #3195933) | Cod sursa (job #2130947)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
const int nMax = 100005;
const int inf = 1e9;
vector <int> G[nMax];
queue <int> Q;
int dist[nMax];
inline void Bfs(int start, int n) {
Q.push(start);
for(int i = 1; i <= n; i++) {
dist[i] = inf;
}
dist[start] = 0;
while(!Q.empty()) {
int nod = Q.front();
Q.pop();
for(const auto &v : G[nod]) {
if(dist[v] > dist[nod] + 1) {
dist[v] = dist[nod] + 1;
Q.push(v);
}
}
}
}
int main()
{
int n, m, s, x, y;
f >> n >> m >> s;
for(int i = 1; i <= m; i++) {
f >> x >> y;
G[x].push_back(y);
}
Bfs(s, n);
for(int i = 1; i <= n; i++) {
if(dist[i] == inf) {
g << "-1 ";
continue;
}
g << dist[i] << " ";
}
g << "\n";
return 0;
}