Pagini recente » Cod sursa (job #1788357) | Cod sursa (job #1669285) | Cod sursa (job #3242451) | Cod sursa (job #1207434) | Cod sursa (job #1268929)
#include <fstream>
#include <queue>
using namespace std;
ifstream in ("bfs.in");
ofstream out ("bfs.out");
int const N=1000001;
int nodes[N], next[N], last[N],nr =0, cost[N];
queue<int> q;
void addEdge(int x,int y)
{
++nr;
nodes[nr] = y;
next[nr] = last[x];
last[x] = nr;
}
void bfs(int s)
{
int x,currentNode;
cost[s] = 0;
q.push(s);
while(!q.empty())
{
x = q.front();
q.pop();
currentNode = x;
x = last[x];
while(x != 0)
{
if(cost[nodes[x]] == 0 && nodes[x] != s)
{
cost[nodes[x]] = cost[currentNode] + 1;
q.push(nodes[x]);
}
x = next[x];
}
}
}
int main()
{
int i,n,m,x,y,s;
in>>n>>m>>s;
for(i=1;i<=m;i++)
{
in>>x>>y;
addEdge(x,y);
}
bfs(s);
for(i=1;i<=n;i++)
{
if(cost[i] == 0 && i != s) out<<"-1"<<" ";
else out<<cost[i]<<" ";
}
return 0;
}