Let's say I have a weighted graph with weights on both edges and vertices. How do I find the "cheapest" path from a certain node s to a certain node t? My complexity should be O(n2(n+m)).
One way to solve this would be to convert the graph into a new graph in which only edges are weighted, not vertices. To do this, you can split each node apart into two nodes as follows. For any node v, make two new nodes, v1 and v2. All edges that previously entered node v now enter node v1, and all edges that leave node v now leave v2. Then, put an edge between v1 and v2 whose cost is the cost of node v.
In this new graph, the cost of a path from one node to another corresponds to the cost of the original path in the original graph, since all edge weights are still paid and all node weights are now paid using the newly-inserted edges.
Constructing this graph should be doable in time O(m + n), since you need to change each edge exactly once and each node exactly once. From there, you can just use a normal Dijkstra's algorithm to solve the problem in time O(m + n log n), giving an overall complexity of O(m + n log n). If negative weights exist, then you can use the Bellman-Ford algorithm instead, giving a total complexity of O(mn).
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With