Pagini recente » Monitorul de evaluare | Cod sursa (job #3339275) | Cod sursa (job #318175) | Cod sursa (job #1481102) | Cod sursa (job #3317919)
#include <iostream>
#include <unordered_map>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int main(){
int n,m,s;
fin>>n>>m>>s;
unordered_map<int, vector<int>> adj;
unordered_map<int, int> min_nodes;
for(int i = 1; i <= n; i++){
min_nodes[i] = -1;
}
for(int i=0;i<m;i++){
int x,y;
fin>>x>>y;
adj[x].push_back(y);
}
vector<bool> visited(n+1, false);
queue<int> q;
q.push(s);
visited[s] = true;
int dist = 0;
min_nodes[s] = dist;
while(!q.empty()){
int node = q.front();
q.pop();
for(int neighbor: adj[node]){
if(!visited[neighbor]){
min_nodes[neighbor] = dist + 1;
dist++;
visited[neighbor] = true;
q.push(neighbor);
}
}
}
for(int i = 1; i <= n; i++){
fout<<min_nodes[i]<<" ";
}
return 0;
}