Pagini recente » Cod sursa (job #2677631) | Cod sursa (job #1183665) | Cod sursa (job #2513165) | Cod sursa (job #1541254) | Cod sursa (job #1626033)
#include <fstream>
#include <vector>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;
ifstream is("bfs.in");
ofstream os("bfs.out");
int n, m;
vector<int> d;
vector<vector<int>> g;
queue<pair <int, int>> Q;
int main()
{
is >> n >> m;
int x, y, s;
is >> s;
g = vector<vector<int> >(n+1);
d = vector<int>(n+1, INF);
d[s] = 0;
for(int i = 1; i <= m; ++i)
{
is >> x >> y;
g[x].push_back(y);
}
Q.push({s, d[s]});
while(!Q.empty())
{
x = Q.front().first;
Q.pop();
//for(const auto &y : g[x])
for(vector<int>::iterator y = g[x].begin(); y != g[x].end(); ++y)
{
if(d[*y] > d[x] + 1)
{
d[*y] = d[x] + 1;
Q.push({*y, d[*y]});
}
}
}
for(int i = 1; i <= n; ++i)
{
if(d[i] == INF)
os << -1 << ' ';
else
os << d[i] << ' ';
}
is.close();
os.close();
return 0;
}