Pagini recente » Cod sursa (job #541875) | Cod sursa (job #3248246) | Cod sursa (job #1999457) | Cod sursa (job #2735211) | Cod sursa (job #2232625)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int n,m,s;
int viz[100004], cost[100004];
vector <int> v[100004];
queue <int> q;
void citire()
{
f>>n>>m>>s;
int k,i,j;
for(k=1; k<=m; k++)
{
f>>i>>j;
v[i].push_back(j);
}
}
void bfs(int nod)
{
int x,k;
q.push(nod);
viz[nod]=1;
cost[nod]=0;
while(!q.empty())
{
x=q.front();
q.pop();
for(k=0; k<v[x].size(); k++)
if(!viz[v[x][k]] && cost[v[x][k]]>cost[x]+1)
{
q.push(v[x][k]);
cost[v[x][k]]=cost[x]+1;
viz[v[x][k]]=1;
}
}
}
int main()
{
int i;
citire();
for(i=1; i<=n; i++)
cost[i]=1000004;
bfs(s);
for(i=1; i<=n; i++)
if(cost[i]==1000004)
g<<-1<<" ";
else
g<<cost[i]<<" ";
f.close();
g.close();
return 0;
}