Pagini recente » Cod sursa (job #1786988) | Borderou de evaluare (job #1448572) | Cod sursa (job #2901356) | Cod sursa (job #1509686) | Cod sursa (job #3316684)
#include <fstream>
#include <list>
#include <unordered_map>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int v[100001];
int main(){
unordered_map< int, list<int> > g;
queue<int> q;
int n, m, x, y, s, dist[100001], l = 0, noduri_ramase, noduri_urmatoare;
fin >> n >> m >> s;
q.push(s);
v[s] = 1;
dist[s] = 0;
for(int i = 1; i <= n; i++){
dist[i]=-1;
}
for(int i = 0; i < m; i++){
fin >> x >> y;
g[x].push_back(y);
}
noduri_ramase = 1;
noduri_urmatoare = 0;
while(!q.empty()){
if(noduri_ramase == 0){
noduri_ramase = noduri_urmatoare;
noduri_urmatoare = 0;
l++;
}
x = q.front();
q.pop();
dist[x] = l;
noduri_ramase--;
for(int nod : g[x]){
if(!v[nod]){
v[nod] = 1;
q.push(nod);
noduri_urmatoare++;
}
}
}
for(int i = 1; i <= n; i++){
fout << dist[i] << endl;
}
return 0;
}