i need to implement a program that given a directed graph with positive costs at the arcs prints the minimum cost to go from x to y and the minimum numer of steps of all the paths that go from x to y with such minimum cost. I have written a program that does that, but sometimes it takes a path that doesn't have the minimum number of steps. Here's my code:
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;
typedef pair<int, int> Warc;
typedef vector<vector<Warc>> Wgraph;
int dijkstra(const Wgraph& g, int x, int y, vector<int>& p) {
int n = g.size();
vector<int> d(n, INT_MAX); //costs
p = vector<int>(n, -1); //parent of each vertice
d[x] =0;
vector<bool> S(n, false);
priority_queue<Warc, vector<Warc>, greater<Warc>> Q;
Q.push(Warc(0, x));
while(not Q.empty()) {
int u = Q.top().second;
Q.pop();
if(u == y) return d[u];
if(not S[u]) {
S[u] = true;
for(Warc a : g[u]) {
int v = a.second;
int c = a.first;
if(d[v] > d[u] + c) {
d[v] = d[u] + c;
p[v] = u;
Q.push(Warc(d[v], v));
}
}
}
}
return -1;
}
int main() {
int n; //# of vertices
while(cin >> n) {
int m; //# of arcs
cin >> m;
Wgraph g(n);
for(int i = 0; i<m; ++i) {
int u, v;
int c;
cin >> u >> v >> c; // arc: u->v with cost C
g[u].push_back(make_pair(c, v));
}
int x, y;
cin >> x >> y; //origin and end
vector<int> p; //p[i]= parent of vertice i
int path = dijkstra(g, x, y, p);
if(path == -1) cout << "no path from " << x << " to " << y << endl;
else {
int s = 0;
int i = y;
while(i != x) {
++s;
i = p[i];
}
cout << "cost " << path-s << ", " << s << " step(s)" << endl;
}
}
}
Thanks.
Aucun commentaire:
Enregistrer un commentaire