Pagini recente » Cod sursa (job #130350) | Cod sursa (job #2796760) | Cod sursa (job #2960270) | Cod sursa (job #406513) | Cod sursa (job #2683244)
#include <fstream>
#include <iostream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, S, x, y, cost[100005], ok;
bool viz[100005];
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;
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);
delete 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;
}