Pagini recente » Cod sursa (job #157504) | Cod sursa (job #2790400) | Profil CorinaT | Cod sursa (job #756430) | Cod sursa (job #1101486)
#include<vector>
#include<fstream>
#include<queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
#define MAXN 100003
vector<int> G[MAXN];
bool v[MAXN];
queue<int> Q;
int depth[MAXN];
int n,m,s;
int nr;
int read()
{
f>>n;
f>>m;
f>>s;
int x,y;
for(int i=1;i<=m;i++)
{
f>>x;
f>>y;
G[x].push_back(y);
}
return 0;
}
int bfs(int nod)
{
Q.push(nod);
v[nod] = true;
while( !Q.empty() )
{
v[Q.front()] = true;
for(int i=0,length = G[Q.front()].size();i<length;i++)
{
if( v[ G[Q.front()][i] ] != true)
{
Q.push( G[Q.front()][i] );
depth[G[Q.front()][i]] = depth[Q.front()] + 1;
}
}
Q.pop();
}
return 0;
}
int write()
{
for(int i=1;i<=n;i++)
{
if(i == s)
{
g<<0<<" ";
}
else if(depth[i] == 0)
{
g<<-1<<" ";
}
else
g<<depth[i]<<" ";
}
return 0;
}
int main()
{
read();
bfs(s);
write();
return 0;
}