Pagini recente » Cod sursa (job #2836759) | Cod sursa (job #1055178) | Cod sursa (job #230577) | Cod sursa (job #796326) | Cod sursa (job #2683029)
#include <fstream>
#include <iostream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S,x,y,v[100002],cost[100002];
bool viz[100002];
struct nod {
nod* urm;
int val;
};
struct coada {
int cost, nod;
}c[100002], n;
void BFS(int S, nod**l)
{
int ic=0,sf=1;
nod* x;
c[1].nod = S;
v[S] = 1;
c[1].cost = 0;
while (ic < sf)
{
n = c[++ic];
x = l[n.nod];
while (x != nullptr&& viz[x->val] == 0)
{
viz[x->val] = 1;
c[++sf].nod = x->val;
c[sf].cost = n.cost+1;
cost[x->val] = n.cost + 1;
x = x->urm;
}
}
}
int main()
{
nod** l;
fin >> N>>M>>S;
l = new nod*[N];
for (int i = 1; i <= N; i++)
l[i] = nullptr;
while (M)
{
nod* model = new nod();
fin >> x >> y;
model->urm = l[x];
l[x] = model;
l[x]->val = y;
M--;
}
BFS(S,l);
for (int i = 1; i <= N; i++)
{
if (i != S)
{
if (cost[i] != 0)
fout << cost[i] << " ";
else
fout << -1 << " ";
}
else
fout << 0 << " ";
}
return 0;
}