Pagini recente » Cod sursa (job #543201) | Cod sursa (job #2052695) | Cod sursa (job #2355497) | Cod sursa (job #1198447) | Cod sursa (job #2425321)
#include <fstream>
#include <queue>
#include <vector>
#include <climits>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n, s, m;
#define nmax 100000
vector <int> graph[nmax];
void read_data() {
f >> n >> m;
f >> s;
for( int i = 0; i < m; i++ ) {
int x, y;
f >> x >> y;
graph[x].push_back(y);
}
}
int d[nmax], viz[nmax];
void bfs() {
queue <int> coada;
for( int i = 1; i <= n; i++) d[i] = INT_MAX;
viz[s] = 1;
coada.push(s); d[s] = 0;
while( !coada.empty() ) {
int nod = coada.front(); coada.pop();
for( auto x : graph[nod] ) {
if( !viz[x] ) {
if( d[x] > d[nod] + 1 ) {
d[x] = d[nod] + 1;
coada.push(x);
}
}
}
}
}
int main(){
read_data();
bfs();
for( int i = 1; i <= n; i++ )
if( d[i] == INT_MAX ) g << -1 <<" ";
else
g << d[i] << " ";
return 0;
}