问题
Suppose there's an undirected graph and each edge that connects any two nodes has two weights (i.e. distance and cost). I want to get the shortest path, but also make sure I do not go beyond a certain cost.
I've tried implementing Djikstra's and simply backtracking (for lack of a better term) if I exceed the cost, until I traverse the entire graph. However, I'm looking for a faster solution than this. I've also attempted to use a function that creates a weight given the distance and cost of an edge, but I don't think this will return the optimal solution.
Any thoughts?
回答1:
We can convert your graph from the original graph with E
edges and V
vertices (E,V)
to another graph (E, V')
with each node v'xy
in V'
is the minimum distance to travel from start to node x
with cost y
.
So, starting at the start node 0, assuming that we travel to node 1 with distance a and cost b, now, we have our distance matrix:
dist[0][0] = 0, and dist[1][b] = a;
Thus, this problem become a normal Shortest path problem.
回答2:
Take an weighted average of cost and distance and take it as parameter.
Say average, p=w*cost+(1-w)*distance
Now select w as per your cost limit.
Now in any shortest path algorithm will work comparing p.
来源:https://stackoverflow.com/questions/35133996/single-source-shortest-path-with-distance-and-weight-for-each-edge