Pagini recente » Cod sursa (job #1737618) | Cod sursa (job #1276285) | Cod sursa (job #2486162) | Cod sursa (job #2155053) | Cod sursa (job #2355976)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout("bfs.out");
struct coada {
int val;
int dist;
};
int n,m,viz[100002],rasp[100002],conComp,a,b,s,first,last;
coada c[100002];
vector <int> graph[100002];
void bfs (int first, int last){
while (first<=last){
int node=c[first].val;
viz[node]=1;
int dim=graph[node].size();
for (int i=0; i<dim; i++){
if (viz[graph[node][i]]==0){
last++;
viz[graph[node][i]]=1;
c[last].val=graph[node][i];
c[last].dist=c[first].dist+1;
if (rasp[c[last].val]==-1){
rasp[c[last].val]=c[last].dist;
}
}
}
first++;
}
}
int main () {
fin>>n>>m>>s;
for (int i=1; i<=n; i++){
rasp[i]=-1;
}
rasp[s]=0;
for (int i=1; i<=m; i++){
fin>>a>>b;
if (a!=b){
graph[a].push_back(b);
}
}
first=1;
last=1;
c[1].dist=0;
c[1].val=s;
bfs(1,1);
for (int i=1; i<=n; i++){
fout<<rasp[i]<<' ';
}
return 0;
}