Pagini recente » Cod sursa (job #732491) | Rating Mihai-Alexandru Militaru (Mike07) | Cod sursa (job #207569) | Cod sursa (job #1291042) | Cod sursa (job #306828)
Cod sursa(job #306828)
#include <iostream>
using namespace std;
FILE *f = fopen("bfs.in", "r"), *g = fopen("bfs.out", "w");
typedef struct nod{
int val;
nod *urm;
} *pNod;
pNod *a;
int N, M, S;
int *cost, *nod1, *vizitat;
int add(int x, int y)
{
pNod q;
q = new nod;
q -> val = y;
q -> urm = a[x];
a[x] = q;
return 0;
}
int bfs(int Start)
{
for (int i = 1; i <= N; ++i)
nod1[i] = cost[i] = vizitat[i] = 0;
nod1[1] = Start;
cost[Start] = 0;
vizitat[Start] = 1;
int L = 1;
for (int i = 1; i <= L; ++i)
{
pNod q;
for (q = a[nod1[i]]; q != NULL; q = q -> urm)
{
if (!vizitat[q -> val])
{
vizitat[q -> val] = 1;
nod1[++L] = q -> val;
cost[q -> val] = cost[nod1[i]] + 1;
}
}
}
return 0;
}
int main()
{
fscanf(f, "%d %d %d", &N, &M, &S);
a = new pNod[N + 1];
for (int i = 1; i <= N; ++i)
a[i] = NULL;
for (int i = 0; i < M; ++i)
{
int x, y;
fscanf(f, "%d %d", &x, &y);
add(x, y);
}
fclose(f);
cost = new int[N + 1];
nod1 = new int[N + 1];
vizitat = new int[N + 1];
bfs(S);
delete[] nod1;
delete[] vizitat;
for (int i = 1; i <= N; ++i)
if (cost[i])
{
fprintf(g, "%d ",cost[i]);
}
else
{
if (i == S)
{
fprintf(g, "0 ");
}
else
{
fprintf(g, "-1 ");
}
}
delete[] cost;
delete[] a;
fclose(g);
return 0;
}