Pagini recente » Cod sursa (job #2492745) | Cod sursa (job #2982244) | Cod sursa (job #2796134) | Cod sursa (job #2088839) | Cod sursa (job #3163882)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n, m, st, cost[100005];
queue <int> q;
vector <int> a[100005];
void bfs()
{
while(!q.empty()) {
int nod = q.front();
q.pop();
for (int i = 0; i < (int) a[nod].size(); ++i) {
if(cost[a[nod][i]] == -1) {
cost[a[nod][i]] = cost[nod] + 1;
q.push(a[nod][i]);
}
}
}
}
int main()
{
f >> n >> m >> st;
for (int i = 1; i <= m; ++i) {
int x, y;
f >> x >> y;
a[x].push_back(y);
}
for (int i = 1; i <= n; ++i) {
cost[i] = -1;
}
cost[st] = 0;
q.push(st);
bfs();
for (int i = 1; i <= n; ++i) {
g << cost[i] << ' ';
}
return 0;
}