Cod sursa(job #593344)
# include <fstream>
# include <vector>
# include <algorithm>
# define dim 100002
# define pb push_back
using namespace std;
ifstream f ("bfs.in");
ofstream g ("bfs.out");
vector <int> a[dim];
int viz[dim], c[dim], G[dim];
int n, m, s;
void citire()
{
int i, x, y;
f >> n >> m >> s;
for ( i = 1 ; i <= m ; ++ i )
{
f >> x >> y;
a[ x ].pb( y );
}
for ( i = 1 ; i <= n ; ++ i )
G[ i ] = a[ i ].size();
for ( i = 1 ; i <= n ; ++ i )
c[ i ] = -1;
}
void bfs(int x)
{
int i, j, l;
l = 1;
c[ x ] = 0;
viz[ l ] = x;
for ( i = 1 ; i <= l ; ++ i)
for ( j = 0; j < G[ viz[ i ] ]; ++ j)
if(c[ a[ viz[ i ] ][ j ] ] == -1 )
{
l++;
viz[ l ] = a[ viz[ i ] ][ j ];
c[ viz[ l ] ] = c[ viz[ i ] ] + 1;
}
}
void afisare()
{
int i;
for( i = 1 ; i <= n ; ++ i )
g<<c[ i ]<<" ";
g<<"\n";
}
int main()
{
citire();
bfs(s);
afisare();
return 0;
}