Pagini recente » Cod sursa (job #1509138) | Cod sursa (job #1317582) | Cod sursa (job #873008) | Cod sursa (job #1811272) | Cod sursa (job #2604747)
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int t[2][1000005],start[100005],cost[100005];
short int ap[100005];
queue <int>co;
int main()
{
int n,m,s,o,k=0,i,j;
fin>>n>>m>>s;
for(o=1;o<=m;o++)
{
k++;
fin>>i>>j;
t[0][k]=j;
t[1][k]=start[i];
start[i]=k;
}
co.push(s);
ap[s]=1;
cost[s]=0;
while(!co.empty())
{
int nr=co.front();
co.pop();
k=start[nr];
while(t[0][k]!=0)
if(ap[t[0][k]]==0)
{
ap[t[0][k]]=1;
co.push(t[0][k]);
cost[t[0][k]]=cost[nr]+1;
k=t[1][k];
}
else
k=t[1][k];
}
for(i=1;i<=n;i++)
if(cost[i]==0&&i!=s)
fout<<-1<<' ';
else
fout<<cost[i]<<' ';
return 0;
}