Pagini recente » Cod sursa (job #1918152) | Cod sursa (job #410113) | Cod sursa (job #1787832) | Cod sursa (job #2415289) | Cod sursa (job #2256165)
#include <fstream>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
struct Node
{
int node;
Node *next;
} *G[100001];
int N;
void bfs(int S)
{
int Q[100001];
int dist[100001];
for(int i=1; i<=N; i++)
dist[i] = -1;
int first = 0;
int last = 0;
dist[S] = 0;
Q[first] = S;
while(first<=last)
{
for(Node *p = G[Q[first]]; p!=0; p = p->next)
{
if(dist[p->node] == -1)
{
dist[p->node] = dist[Q[first]] + 1;
last++;
Q[last] = p->node;
}
}
first++;
}
for(int i=1; i<=N; i++)
fout << dist[i] << ' ';
}
int main()
{
int M, S;
fin >> N >> M >> S;
while(M)
{
int x, y;
fin >> x >> y;
Node *p = new Node;
p->node = y;
p->next = G[x];
G[x] = p;
M--;
}
bfs(S);
fin.close();
fout.close();
return 0;
}