Pagini recente » Cod sursa (job #268870) | Cod sursa (job #319761) | Cod sursa (job #2147227) | Cod sursa (job #1275662) | Cod sursa (job #1869021)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int NMAX = 100000 + 5;
queue <int> q;
vector <int> graph[NMAX];
bool vis[NMAX];
int dist[NMAX];
int cnt, n, m, s;
void Read()
{
fin >> n >> m >> s;
for (int i = 1; i <= m; ++i)
{
int a, b;
fin >> a >> b;
graph[a].push_back(b);
}
}
void bfs()
{
int nod;
vis[s] = 1;
q.push(s);
while(!q.empty())
{
nod = q.front();
q.pop();
for (int i = 0; i < graph[nod].size(); ++i)
{
if(vis[graph[nod][i]])
{
vis[graph[nod][i]] = 1;
dist[graph[nod][i]] = dist[nod] + 1;
q.push(graph[nod][i]);
}
}
}
}
int main()
{
Read();
bfs();
for (int i = 1; i <= n; ++i)
{
if (!vis[i])
fout << -1;
else
fout << dist[i];
if(i == n)
fout << '\n';
else
fout << " ";
}
return 0;
}