Pagini recente » Cod sursa (job #269415) | Cod sursa (job #1246716) | Cod sursa (job #2769481) | Cod sursa (job #1050272) | Cod sursa (job #3271933)
#include <fstream>
#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>
#define MAXN 100010
using namespace std;
ifstream fin("bfs.in");
ofstream fout("bfs.out");
int N, M, root, pathEnd;
int x, y;
vector<int> L[MAXN];
deque<int> q;
int d[MAXN];
int pred[MAXN];
void printPath(int s, int x)
{
vector<int> path;
for (int node = x; node != 0; node = pred[node])
path.push_back(node);
reverse(path.begin(), path.end());
for (const auto el : path)
{
cout << el << " ";
}
}
void bfs(int root, int pathEnd)
{
q.push_back(root);
d[root] = 1;
while(!q.empty())
{
int node = q.front();
for (const auto nextNode : L[node])
{
if (d[nextNode] == 0)
{
q.push_back(nextNode);
d[nextNode] = d[node] + 1;
pred[nextNode] = node;
}
}
q.pop_front();
}
if (d[pathEnd] == 0) {
cout << "No path from " << root << " to " << pathEnd << endl;
} else {
cout << "Shortest path from " << root << " to " << pathEnd << ": ";
printPath(root, pathEnd);
}
}
int main()
{
fin >> N >> M >> root >> pathEnd;
for (int i = 1; i <= M; i++)
{
fin >> x >> y;
L[x].push_back(y);
}
bfs(root, pathEnd);
for (int i = 1; i <= N; i++)
{
fout << d[i] - 1 << " ";
}
return 0;
}