Pagini recente » Cod sursa (job #1128727) | Cod sursa (job #2949261) | Cod sursa (job #2400085) | Cod sursa (job #1831874) | Cod sursa (job #1806294)
#include <fstream>
#include <cstring>
#include <queue>
#define nmax 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
queue < int > neighbours_for[nmax], tail;
int number_vertices, number_edges, first_vertex, distance_to[nmax], x, y;
bool was_here[nmax];
void read_input() {
fin >> number_vertices >> number_edges >> first_vertex;
for (int i = 1; i <= number_edges; ++i) {
fin >> x >> y;
neighbours_for[x].push(y);
}
}
void breadth_first_algorithm() {
tail.push(first_vertex);
distance_to[first_vertex] = 0;
was_here[first_vertex] = true;
while (!tail.empty()) {
x = tail.front();
tail.pop();
while (!neighbours_for[x].empty()) {
if (!was_here[neighbours_for[x].front()]) {
distance_to[neighbours_for[x].front()] = distance_to[x] + 1;
was_here[neighbours_for[x].front()] = true;
tail.push(neighbours_for[x].front());
}
neighbours_for[x].pop();
}
}
}
void type_results() {
for (int i = 1; i <= number_vertices; ++i)
fout << distance_to[i] << " ";
}
int main()
{
memset(distance_to, -1, sizeof(distance_to));
read_input();
breadth_first_algorithm();
type_results();
return 0;
}