Pagini recente » Cod sursa (job #121342) | Cod sursa (job #1698220) | Cod sursa (job #1917860) | Cod sursa (job #1762119) | Cod sursa (job #2237088)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
#define MAXN 100005
#define INF 0x3f3f3f3f
int main() {
int n, m, s;
fin >> n >> m >> s;
vector<int> dist(n + 5, INF);
vector<int> graf[MAXN];
for(int i = 1; i <= m; i++) {
int x, y;
fin >> x >> y;
graf[x].push_back(y);
}
queue<int> q;
q.push(s);
dist[s] = 0;
while(!q.empty()) {
int crtNode = q.front(); q.pop();
for(auto nextNode: graf[crtNode]) {
if(dist[nextNode] > dist[crtNode] + 1) {
dist[nextNode] = dist[crtNode] + 1;
q.push(nextNode);
}
}
}
for(int i = 1; i <= n; i++) {
if(dist[i] == INF)
fout << "-1 ";
else
fout << dist[i] << " ";
}
return 0;
}