I need to alter the code a little so that it displays not just the final result, for example, from 1 to 4: 1 -> 2 -> 5 -> 4, but also intermediate passes (steps to search for a short path), for example, from 1 went to 2, then to 3, that is, 1 -> 2, 1 -> 3; then from 2 ways, for example 2 -> 7, 2 -> 5, etc.
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include <algorithm> using namespace std; const int n = 10; const int inf = 1000*1000*1000; int start, g[n][n]= { {0, 20, 25, 30, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 5, 0, 10, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 10, 15, 0, 0, 0}, {0, 0, 0, 0, 25, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 15, 0, 5, 10, 20}, {0, 0, 0, 0, 15, 0, 10, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 15, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 10}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 10}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }; int main() { vector <int> d(n+5,inf),p(n+5,-1); vector <bool> used(n+5); int start = 0, finish = 9,mn,u; d[start] = 0; for (int i=0;i<n;++i){ mn = inf, u = -1; for (int j=0;j<n;++j) if (!used[j] && d[j] < mn) mn = d[j], u = j; if (u == -1) break; used[u] = true; for (int j=0;j<n;++j) if (d[j] > d[u] + g[u][j] && g[u][j] > 0 ) d[j] = d[u] + g[u][j], p[j] = u; } vector <int> v; if (p[finish] == -1) cout<<"No way\n"; else{ for (int u = finish ; u != -1; u = p[u]) v.push_back(u); reverse(v.begin(),v.end()); for (int i=0;i<v.size();++i){ if (i > 0) cout<<"->"; cout<<v[i]; } } cout<<"\n"<<d[finish]<<"\n"; }
d[j] = d[u] + g[u][j], p[j] = u;in the same condition - pavel