Pagini recente » Cod sursa (job #814481) | Cod sursa (job #1320245) | Cod sursa (job #2785612) | Cod sursa (job #764252) | Cod sursa (job #1101508)
#include<vector>
#include<fstream>
#include<queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
#define MAXN 100003
vector<int> G[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);
depth[nod] = 0;
while( !Q.empty() )
{
for(int i=0,length = G[Q.front()].size();i<length;i++)
{
if( depth[ G[Q.front()][i] ] == -1 && depth[ G[Q.front()][i] ] != 0 )
{
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++)
{
g<<depth[i]<<" ";
}
return 0;
}
int main()
{
read();
for(int i=1;i<=n;i++)
{
depth[i] = -1;
}
bfs(s);
write();
return 0;
}