Pagini recente » Cod sursa (job #1264581) | Cod sursa (job #2122405) | Cod sursa (job #2485245) | Cod sursa (job #1962954) | Cod sursa (job #3314242)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
vector<int> a[100005];
int cost[100005];
void bfs(int nod)
{
queue<int> q;
q.push(nod);
cost[nod] = 0;
while (!q.empty())
{
int actNod = q.front();
q.pop();
for (auto next : a[actNod])
if (cost[next] > cost[actNod] + 1)
{
cost[next] = cost[actNod] + 1;
q.push(next);
}
}
}
int main()
{
int n, m, s;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
fin >> n >> m >> s;
for (int i = 1; i <= m; i++)
{
int x, y;
fin >> x >> y;
a[x].push_back(y);
}
for (int i = 0; i <= 100000; i++)
cost[i] = 1e9;
bfs(s);
for (int i = 1; i <= n; i++)
fout << ((cost[i] == 1e9) ? -1 : cost[i]) << ' ';
fout << '\n';
return 0;
}