Pagini recente » Cod sursa (job #2894424) | Cod sursa (job #2531531) | Cod sursa (job #1352847) | Cod sursa (job #749684) | Cod sursa (job #2550924)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
vector < int > v[100002];
queue < int > q;
int cost[100002];
int main() {
ifstream f("bfs.in");
ofstream g("bfs.out");
int n, m, s;
f >> n >> m >> s;
for(int i = 1; i <= m; i++) {
int x, y; f >> x >> y;
v[x].push_back(y);
}
memset(cost, -1, sizeof(cost));
cost[s] = 0;
q.push(s);
while(!q.empty()) {
int x = q.front();
q.pop();
for(int i = 0; i < v[x].size(); i++)
if(cost[v[x][i]] == -1) {
q.push(v[x][i]);
cost[v[x][i]] = cost[x] + 1;
}
}
for(int i = 1; i <= n; i++)
g << cost[i] << ' ';
g << '\n';
f.close();
g.close();
return 0;
}