Pagini recente » Profil Vladinho96 | Rating Pavel Mihai (mpavel77) | Profil tabara | Berarii2 | Cod sursa (job #2016045)
#include <stdio.h>
#include <vector>
using namespace std;
#define maxn 100010
int n,m,s,L,cost[maxn],G[maxn],S[maxn];
vector <int> A[maxn];
void Read()
{
int aux1,aux2;
freopen("bfs.in","r",stdin);
freopen("bfs.out","w",stdout);
scanf("%i %i %i",&n,&m,&s);
for(int i=1;i<=m;i++)
{
scanf("%i %i",&aux1,&aux2);
A[aux1].push_back(aux2);
}
for(int i=1;i<=n;i++)
{
G[i] = A[i].size(); // numarul vecinilor
}
}
void BFS(int nod)
{
for(int i=1;i<=n;i++)
{
cost[i] = -1;
}
L = 1;
cost[nod] = 0;
S[L] = nod;
for(int i=1;i<=L;i++)
{
for(int j=0;j<G[S[i]];j++)
{
if(cost[A[S[i]][j]] == -1)
{
L++;
S[L] = A[S[i]][j];
cost[S[L]] = cost[S[i]] + 1;
}
}
}
}
int main()
{
Read();
BFS(s);
for(int i=1;i<=n;i++)
printf("%i ",cost[i]);
return 0;
}