3.The Flight Plan
Spoj Question
Solution: (Using BFS)
#include <bits/stdc++.h>
using namespace std;
void bfs(int node, int target, vector<int> v[], vector<bool> &vs, vector<int> &dist, vector<int> &pred)
{
queue<int> q;
q.push(node);
vs[node] = 1;
pred[node] = -1;
while (!q.empty())
{
int x = q.front();
int d = dist[x];
q.pop();
if (x == target)
{
return;
}
for (auto itr = v[x].begin(); itr != v[x].end(); itr++)
{
if (vs[*itr] == 0)
{
q.push(*itr);
vs[*itr] = 1;
dist[*itr] = d + 1;
pred[*itr] = x;
}
}
}
return;
}
int main()
{
vector<int> sol;
int n, m, t, c;
cin >> n >> m >> t >> c;
vector<int> v[n + 1];
vector<bool> vs(n + 1);
vector<int> dist(n + 1);
vector<int> pred(n + 1);
for (int i = 1; i <= m; i++)
{
int a, b;
cin >> a >> b;
v[a].push_back(b);
v[b].push_back(a);
}
for (int i = 1; i <= n; i++)
{
sort(v[i].begin(), v[i].end());
}
int x, y;
cin >> x >> y;
bfs(x, y, v, vs, dist, pred);
cout << dist[y] + 1 << "\n";
sol.push_back(y);
while (pred[y] != -1)
{
sol.push_back(pred[y]);
y = pred[y];
}
for (int i = sol.size() - 1; i >= 0; i--)
{
cout << sol[i] << " ";
}
return 0;
}Last updated