Pagini recente » Cod sursa (job #1874598) | Cod sursa (job #93068) | Cod sursa (job #1453344) | Cod sursa (job #321874) | Cod sursa (job #2073731)
#include<fstream>
#include<list>
#include<queue>
using namespace std;
ifstream f("bfs.in");
ofstream g("bfs.out");
list<int>l[100005];
queue<int>c;
bool viz[100005];
int cost[100005];
int n, m, nr_comp, s;
void citire()
{
f >> n >> m >> s;
int x, y;
while(f >> x >> y)
l[x].push_back(y);
}
void bfs(){
c.push(s);
viz[s] = 1;
cost[s] = 0;
while(!c.empty()){
int nc = c.front();
list<int>::iterator it;
for(it = l[nc].begin(); it != l[nc].end(); it++){
if(!viz[*it]){
cost[*it] = cost[nc] + 1;
c.push(*it);
viz[*it] = true;
}
}
c.pop();
}
for(int i = 1; i <= n; i++)
if(cost[i] == 0)
cost[i] = -1;
}
void solve(){
bfs();
cost[s] = 0;
for(int i = 1; i <= n; i++)
g << cost [i] << ' ';
}
int main(){
citire();
solve();
return 0;
}