Pagini recente » Cod sursa (job #645879) | Cod sursa (job #1351214) | Cod sursa (job #1983340) | Statisticile problemei Cars | Cod sursa (job #1999569)
#include <fstream>
using namespace std;
ifstream cin("bfs.in");
ofstream cout("bfs.out");
const int MAX = 1e5 + 1;
struct nod {
int info;
nod *urm;
};
struct coada {
nod *st, *fin;
coada() {
st = fin = NULL;
}
void push(int x) {
nod *nou = new nod;
nou->info = x;
nou->urm = NULL;
if(st == NULL) {
st = fin = nou;
} else {
fin->urm = nou;
fin = nou;
}
}
int pop() {
if(st == NULL) {
return 0;
}
int ans = st->info;
if(st == fin) {
delete st;
st = fin = NULL;
} else {
nod *del = st;
st = st->urm;
delete del;
}
return ans;
}
bool empty() {
return st == NULL;
}
};
int n, m, s, dist[MAX];
coada gr[MAX], q;
void bfs() {
for(int i = 1; i <= n; ++i)
dist[i] = -1;
dist[s] = 0;
q.push(s);
while(!q.empty()) {
int varf = q.pop();
for(nod *i = gr[varf].st; i != NULL; i = i->urm) {
int fiu = i->info;
if(dist[fiu] == -1) {
dist[fiu] = 1 + dist[varf];
q.push(fiu);
}
}
}
}
int main()
{
cin >> n >> m >> s;
for(int i = 1; i <= m; ++i) {
int x, y;
cin >> x >> y;
gr[x].push(y);
}
bfs();
for(int i = 1; i <= n; ++i) {
cout << dist[i] << ' ';
}
return 0;
}