Pagini recente » Cod sursa (job #1983490) | Cod sursa (job #592862) | Monitorul de evaluare | Cod sursa (job #2331352) | Cod sursa (job #1867647)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
struct Node
{
int cost = -1;
vector<int> edges;
};
using Graph = vector<Node>;
void Bfs(Graph &g, int start)
{
queue<int> q;
q.push(start);
g[start].cost = 0;
while (!q.empty()) {
int node = q.front();
q.pop();
for (int next : g[node].edges) {
if (g[next].cost == -1) {
g[next].cost = g[node].cost + 1;
q.push(next);
}
}
}
}
int main()
{
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, s;
fin >> n >> m >> s;
Graph graph(n);
while (m--) {
int x, y;
fin >> x >> y;
graph[x - 1].edges.push_back(y - 1);
}
Bfs(graph, s - 1);
for (const auto &node : graph) {
fout << node.cost << " ";
}
fout << "\n";
return 0;
}