Pagini recente » Profil 4giannac1122eL3 | Cod sursa (job #2653008)
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
vector<int> v[100005];
queue<int> q;
bool vs[100005];
int vr[100005];
void edge(int x,int y)
{
v[x].push_back(y);
}
void bfs(int n)
{
int x;
while(v[n].empty()==false)
{
x=v[n].back();
v[n].pop_back();
if(vs[x]==0)
{
vs[x]=1;
q.push(x);
vr[x]=vr[n]+1;
}
}
if(q.empty()==false)
{
x=q.front();
q.pop();
bfs(x);
}
}
int main()
{
ifstream cin("bfs.in");
ofstream cout("bfs.out");
int n,m,s,x,y;
cin >> n >> m >> s;
fill_n (vr+1, n, -1);
for(int i=0;i<m;i++)
{
cin >> x >> y;
if(x!=y)
edge(x,y);
}
vs[s]=1;
vr[s]=0;
bfs(s);
for(int i=1;i<=n;i++)
{
if(vs[i]==0)
cout << -1 << " ";
else
{
cout << vr[i] << " ";
}
}
return 0;
}