Pagini recente » Cod sursa (job #686219) | Cod sursa (job #512598) | Cod sursa (job #1316594) | Cod sursa (job #792773) | Cod sursa (job #1378888)
#include <vector>
#include <fstream>
#include <queue>
#define Inf 0x3f3f3f3f
using namespace std;
ifstream is("bfs.in");
ofstream os("bfs.out");
int n, m, s;
int cnt;
vector<vector<int>> g;
vector<int> d;
queue <pair<int, int>> Q;
vector<bool> sel;
int main()
{
is >> n >> m >> s;
int x, y;
g = vector<vector<int>>(n+1);
d = vector<int>(n + 1, Inf);
sel = vector<bool>(n + 1);
for(int i = 1; i <= m; ++i)
{
is >> x >> y;
g[x].push_back(y);
}
Q.push({s, 0});
d[s] = 0;
int k;
while(!Q.empty())
{
k = Q.front().first;
Q.pop();
for(vector<int>::iterator it = g[k].begin(); it != g[k].end(); ++it)
{
if(!sel[*it] && d[*it] > d[k] + 1)
{
sel[*it] = true;
d[*it] = d[k] + 1;
Q.push({*it, d[y]});
}
}
}
for(int i = 1; i <= n; ++i)
{
if(d[i] == Inf)
d[i] = -1;
}
for(int i = 1; i <= n; ++i)
{
os << d[i] << ' ';
}
is.close();
os.close();
return 0;
}