Pagini recente » Cod sursa (job #2708382) | Cod sursa (job #333291) | Cod sursa (job #2640382) | rar18 | Cod sursa (job #2864689)
#include <fstream>
#include <vector>
#include <queue>
#define MAX_N 100000
using namespace std;
vector<int> graph[MAX_N + 1];
queue<int> bfsQueue;
int dist[MAX_N + 1];
int N, M, S;
ifstream in ("bfs.in");
ofstream out ("bfs.out");
void fix(int N){
for (int i = 1; i <= N; i ++)
dist[i] = -1;
}
void addEdge(int a, int b){
graph[a].push_back(b);
}
void bfs(int node){
dist[node] = 0;
bfsQueue.push(node);
while(!bfsQueue.empty()){
int firstNode = bfsQueue.front();
for (int neighbour : graph[firstNode]){
if (dist[neighbour] == -1){
dist[neighbour] = dist[firstNode] + 1;
bfsQueue.push(neighbour);
}
}
bfsQueue.pop();
}
}
int main(){
in >> N >> M >> S;
fix(N);
int a , b;
for(int i = 0; i < M; i ++){
in >> a >> b;
addEdge(a, b);
}
bfs(S);
for (int i = 1; i <= N; i ++)
out << dist[i] << " ";
out << '\n';
}