Pagini recente » Cod sursa (job #3198487) | Cod sursa (job #3208662)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bfs.in");
ofstream fout ("bfs.out");
const int NMAX = 1e5;
vector <int> graph[NMAX + 5];
queue <int> q;
int dp[NMAX + 5];
void bfs(int source)
{
q.push(source);
while(!q.empty())
{
int node = q.front();
q.pop();
for(auto neigh : graph[node])
{
if(dp[neigh] == -1 or dp[neigh] > dp[node] + 1)
{
dp[neigh] = dp[node] + 1;
q.push(neigh);
}
}
}
}
int main()
{
int n, m, s;
fin >> n >> m >> s;
for(int i = 1; i <= m; i++)
{
int u, v;
fin >> u >> v;
graph[u].push_back(v);
}
for(int i = 1; i <= n; i++)
dp[i] = -1;
dp[s] = 0;
bfs(s);
for(int i = 1; i <= n; i++)
fout << dp[i] << ' ';
fin.close();
fout.close();
return 0;
}