Pagini recente » Cod sursa (job #571777) | Cod sursa (job #1090879) | Cod sursa (job #2254472) | Cod sursa (job #2328024) | Cod sursa (job #2168205)
#include <fstream>
#include <queue>
#include <vector>
#define NMAX 100001
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
struct node
{
int x;
node* next;
};
typedef node* LSI;
int n, m, start, lg[NMAX];
LSI LAD[NMAX];
queue <int> coada;
void BFS();
void insert(LSI& l, int x);
int main()
{
int i, x, y;
fin >> n >> m >> start;
for (i = 1; i <= m; i++)
{
fin >> x >> y;
if (x != y)
insert(LAD[x], y);
}
BFS();
lg[start] = -1;
for (i = 1; i <= n; i++)
if (lg[i] > 0)
fout << lg[i] << ' ';
else
if (lg[i] == 0)
fout << -1 << ' ';
else
fout << 0 << ' ';
return 0;
}
void BFS()
{
int x;
node* p;
coada.push(start);
while (!coada.empty())
{
x = coada.front(); coada.pop();
for (p = LAD[x]; p; p = p->next)
if (!lg[p->x])
{
coada.push(p->x); lg[p->x] = lg[x] + 1;
}
}
}
void insert(LSI& l, int x)
{
node* p = new node;
p->x = x;
p->next = l;
l = p;
}