Pagini recente » Cod sursa (job #1108538) | Cod sursa (job #2297589) | Cod sursa (job #574806) | Cod sursa (job #226795) | Cod sursa (job #1610440)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
vector<int> graph[100000];
int dist[100000];
queue<int> q;
void bfs(int node) {
q.push(node);
dist[node] = 0;
while (!q.empty()) {
int x = q.front();
q.pop();
for(int i = 0; i < graph[x].size(); ++i) {
if (dist[graph[x][i]] == -1) {
q.push(graph[x][i]);
dist[graph[x][i]] = dist[x]+1;
}
}
}
}
int main() {
ifstream input;
ofstream output;
input.open("bfs.in");
output.open("bfs.out");
int n,m,s;
input >> n >> m >> s;
for(int i=0; i < m; ++i) {
int x,y;
input >> x >> y;
graph[x-1].push_back(y-1);
}
fill_n(dist, n, -1);
bfs(s-1);
for(int i=0; i < n; ++i)
output << dist[i] << ' ';
input.close();
output.close();
}