Pagini recente » Cod sursa (job #1069405) | Cod sursa (job #1251567) | Cod sursa (job #2414679) | Cod sursa (job #977800) | Cod sursa (job #1884500)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
int N, M, X;
int d[100001], viz[100001];
vector<int> v[100000];
void bfs(int nod)
{
int i, x;
queue<int> q;
q.push(nod);
viz[nod] = 1;
while(!q.empty())
{
x = q.front();
q.pop();
while(!v[x].empty())
{
if(!viz[v[x].front()])
{
viz[v[x].front()] = 1;
d[v[x].front()] = d[x] + 1;
q.push(v[x].front());
}
v[x].erase(v[x].begin());
}
}
for(i = 1; i < N + 1; i++)
if(viz[i] == 0)
{
if(i == X)
g << "0 ";
else
g << "-1 ";
}
else
g << d[i] << " ";
}
int main()
{
int i;
f >> N >> M >> X;
for(i = 0; i < M; i++)
{
int a, b;
f >> a >> b;
v[a].push_back(b);
}
bfs(X);
return 0;
}