Pagini recente » Cod sursa (job #2108638) | Cod sursa (job #2849893) | Cod sursa (job #1345708) | Cod sursa (job #2088728) | Cod sursa (job #1804140)
#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;
void read_input() {
fin >> number_vertices >> number_edges >> first_vertex;
for (int i = 1; i <= number_edges; ++i) {
int x, y;
fin >> x >> y;
neighbours_for[x].push(y);
}
}
void breadth_first_algorithm_and_type_results() {
bool was_here[number_vertices];
memset(was_here, false, sizeof(was_here));
int distance_to[number_vertices];
memset(distance_to, -1, sizeof(distance_to));
tail.push(first_vertex);
distance_to[first_vertex] = 0;
was_here[first_vertex] = true;
while (!tail.empty()) {
int 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();
}
}
for (int i = 1; i <= number_vertices; ++i)
fout << distance_to[i] << " ";
}
int main()
{
read_input();
breadth_first_algorithm_and_type_results();
return 0;
}