Pagini recente » Cod sursa (job #1496414) | Cod sursa (job #3128865) | Cod sursa (job #2312206) | Cod sursa (job #1028067) | Cod sursa (job #2231206)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 100005;
int dist[MAXN];
vector<int> graf[MAXN];
queue<int> Q;
const int inf = 1e9;
int main()
{
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
fin >> n >> m >> s;
int x, y;
for(int i = 1; i <= m; ++i){
fin >> x >> y;
graf[x].push_back(y);
}
for(int i = 1; i <= n; ++i)
dist[i] = inf;
dist[s] = 0;
Q.push(s);
while(!Q.empty()){
int curr = Q.front();
Q.pop();
if(graf[curr].size()){
for(int i = 0; i < int(graf[curr].size()); ++i){
if(dist[graf[curr][i]] > dist[curr] + 1){
Q.push(graf[curr][i]);
dist[graf[curr][i]] = dist[curr] + 1;
}
}
}
}
for(int i = 1; i <= n; ++i){
if(dist[i] < inf)
fout << dist[i] << " ";
else
fout << -1 << " ";
}
return 0;
}