Pagini recente » Cod sursa (job #1085056) | Cod sursa (job #1386652) | Cod sursa (job #1519291) | Cod sursa (job #3259739) | Cod sursa (job #1808142)
#include <fstream>
#include <cstring>
#include <queue>
#include <vector>
#define nmax 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
queue < int > tail;
vector < int > neighbours_for[nmax];
int number_vertices, number_edges, first_vertex, distance_to[nmax];
bool was_here[nmax];
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_back(y);
}
}
void breadth_first_algorithm() {
tail.push(first_vertex);
distance_to[first_vertex] = 0;
was_here[first_vertex] = true;
while (!tail.empty()) {
int x = tail.front();
tail.pop();
for (int i = 0; i <= neighbours_for[x].size() - 1; ++i)
if (!was_here[neighbours_for[x][i]]) {
distance_to[neighbours_for[x][i]]= distance_to[x] + 1;
was_here[neighbours_for[x][i]] = true;
tail.push(neighbours_for[x][i]);
}
}
}
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;
}