Pagini recente » Cod sursa (job #1599658) | Cod sursa (job #1142209) | Cod sursa (job #1566788) | Cod sursa (job #3294312) | Cod sursa (job #2628680)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
vector <int> graph[100001];
vector <int> dist;
int tail[100001];
void bfs(int node, int n) {
int first = 0, last = 0;
tail[0] = node;
dist[node] = 0;
while (first <= last) {
for (vector <int> :: iterator it = graph[tail[first]].begin(); it != graph[tail[first]].end(); it++)
if (dist[*it] == -1) {
tail[++last] = *it;
dist[*it] = dist[tail[first]] + 1;
}
first++;
}
}
int main() {
int n, m, node;
fin >> n >> m >> node;
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
graph[x].push_back(y);
}
dist.assign(n + 1, -1);
bfs(node, n);
for (vector <int> :: iterator it = dist.begin() + 1; it != dist.end(); it++)
fout << *it << " ";
return 0;
}