Pagini recente » Cod sursa (job #1218943) | Cod sursa (job #1679802) | Cod sursa (job #1279567) | Cod sursa (job #1424157) | Cod sursa (job #2683052)
#include <fstream>
#include <iostream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S,x,y,cost[100100],ok;
bool viz[100100];
struct nod {
nod* urm;
int val;
};
struct coada {
int cost, nod;
}c[100100], n;
void BFS(int S, nod**l)
{
int ic=0,sf=1;
nod* x;
c[1].nod = S;
viz[S] = 1;
c[1].cost = 0;
while (ic < sf)
{
n = c[++ic];
x = l[n.nod];
while (x != nullptr) {
if (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;
}
else
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)
{
ok = 0;
nod* model;
fin >> x >> y;
model = new nod;
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;
}