Pagini recente » Cod sursa (job #1305944) | Cod sursa (job #2744556) | Cod sursa (job #701045) | Cod sursa (job #2223564) | Cod sursa (job #1006731)
#include <fstream>
#include <algorithm>
#include <queue>
#include <iostream>
#include <list>
#define NMAX 100005
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int n, m, cost[NMAX], p,i,x,y,a[3][1000010],k,start[100010],j;
queue <int> q;
void bfs(int nod) {
int p, y;
cost[nod] = 0;
q.push(nod);
while (!q.empty()) {
p = q.front();
q.pop();
// vizitam toti vecinii punctului scos din coada
x=start[p];
while(x!=0)
{
if(cost[a[0][x]] ==-1)
{
cost[a[0][x]]=cost[p]+1;
q.push(a[0][x]);
}
x=a[1][x];
}
}
}
void setcost() {
for (int i = 1; i <= n; i++)
cost[i] = -1;
}
void afiscost() {
for (int i = 1; i <= n; i++)
fout << cost[i] << ' ';
fout.close();
}
int main() {
fin >> n >> m >> p;
k=0;
for (i = 1; i <= m; i++) {
fin >> x >> y;
k++;
a[0][k]=y;
a[1][k]=start[x];
start[x]=k;
}
setcost();
bfs(p);
afiscost();
}