Pagini recente » Cod sursa (job #3173539) | Cod sursa (job #896261) | Cod sursa (job #1995355) | Cod sursa (job #3223042) | Cod sursa (job #1355729)
#include <cstdio>
#include <queue>
using namespace std;
const int MAX_N = 100000, MAX_M = 1000000;
FILE *in, *out;
int lst[MAX_N+1], urm[MAX_M+1], vf[MAX_M+1];
int nr;
void add(int x, int y)
{
nr++;
vf[nr] = y;
urm[nr] = lst[x];
lst[x] = nr;
}
queue<int> q;
bool viz[MAX_N+1];
int d[MAX_N+1];
void bfs()
{
int x, p;
while(!q.empty())
{
x = q.front();
q.pop();
viz[x] = true;
p = lst[x];
while(p != 0)
{
if(!viz[vf[p]])
{
q.push(vf[p]);
d[vf[p]] = d[x]+1;
}
p = urm[p];
}
}
}
int main()
{
in = fopen("bfs.in", "r");
out = fopen("bfs.out","w");
int n, m, s;
int x, y;
fscanf(in, "%d%d%d", &n, &m, &s);
for(int i = 1; i <= m; i++)
{
fscanf(in, "%d%d", &x, &y);
add(x, y);
}
d[s] = 1;
q.push(s);
bfs();
for(int i = 1; i <= n; i++)
fprintf(out, "%d ", d[i]-1);
fclose(in);
fclose(out);
return 0;
}