Pagini recente » Cod sursa (job #2224672) | Cod sursa (job #774259) | Istoria paginii runda/simulare_lot_seniori_2 | Cod sursa (job #904678) | Cod sursa (job #1323512)
#include <fstream>
#include <vector>
#include <list>
#include <queue>
std::ifstream in ("bfs.in");
std::ofstream out ("bfs.out");
int n, m, first;
std::vector< std::list<int> > x;
std::vector<int> dist;
std::vector<bool> seen;
void bfs (int first)
{
std::queue<int> q;
q.push (first);
int current;
std::list<int>::iterator i;
while (not q.empty()) {
current = q.front(); q.pop();
for (i = x[current].begin(); i != x[current].end(); i++)
if (!seen[*i]) {
seen[*i] = true;
dist[*i] = dist[current] + 1;
q.push (*i);
}
}
}
int main()
{
in >> n >> m >> first;
x.resize (n+1);
dist.resize (n+1, 0);
seen.resize (n+1, false);
int a, b, i;
for (i=0; i<m; i++) {
in >> a >> b;
if (a == b && a == first) {
seen[first] = true;
}
x[a].push_back (b);
}
bfs (first);
dist[first] = -1;
for (i=1; i<=n; i++) {
if (dist[i] == 0) out << "-1 ";
else if (dist[i] == -1) out << "0 ";
else out << dist[i] << " ";
}
}