Pagini recente » Istoria paginii runda/concurs_2/clasament | Cod sursa (job #12946) | Arhiva de probleme | Implica-te! | Cod sursa (job #974769)
Cod sursa(job #974769)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
const int MAXN = 100003;
queue<int> coada;
int n, m, s, a, b, pkt, nr, i;
struct nod {
int cost;
vector<int> neighbours;
}nods[MAXN];
void read() {
fin >> n >> m >> s;
for (int i = 1; i <= m; ++i) {
fin >> a >> b;
nods[a].neighbours.push_back(b);
}
}
void go() {
coada.push(s);
nods[s].cost = 0;
do {
pkt = coada.front();//nodul actual
coada.pop();
nr = nods[pkt].neighbours.size();//nr vecini
for (int i = 0; i < nr; ++i) {//parcurg toti vecinii
if (nods[pkt].cost + 1 < nods[nods[pkt].neighbours[i]].cost) {
nods[nods[pkt].neighbours[i]].cost = nods[pkt].cost + 1;
coada.push(nods[pkt].neighbours[i]);
}
}
}while (!coada.empty());
}
int main() {
read();
for (i = 1; i <= n; ++i)
nods[i].cost = MAXN + 10;
go();
for (i = 1; i <= n; ++i) {
if (nods[i].cost == MAXN + 10)
fout << -1 << ' ';
else
fout << nods[i].cost << ' ';
}
fout << '\n';
fin.close();
fout.close();
return 0;
}