Pagini recente » Cod sursa (job #687713) | Cod sursa (job #2242096) | Cod sursa (job #1263025) | Cod sursa (job #309505) | Cod sursa (job #3251416)
#include <vector>
#include <queue>
#include <cstring>
#include <fstream>
using namespace std;
#define maxn 1000000
ifstream in("bfs.in");
ofstream out("bfs.out");
vector<int> ad[maxn];
int cost[maxn];
void bfs(int s)
{
memset(cost, -1, sizeof(cost)); // initialize the cost array
queue<int> q;
cost[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v : ad[u])
{
if (cost[v] == -1)
{
cost[v] = cost[u] + 1;
q.push(v);
}
}
}
}
int main()
{
int n, m, s, x, y;
in >> n >> m >> s;
for (int i = 0; i < m; ++i)
{
in >> x >> y;
ad[x].push_back(y);
}
bfs(s);
for (int i = 1; i <= n; ++i)
{
out << cost[i] << ' ';
}
return 0;
}