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)).
相关问题
- Faster loop: foreach vs some (performance of jsper
- Why wrapping a function into a lambda potentially
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
相关文章
- Mercurial Commit Charts / Graphs [closed]
- What is the complexity of bisect algorithm?
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Should client-server code be written in one “proje
- DOM penalty of using html attributes
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 v1.
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!
Following modification of Djkstra should work
I think it's possible to convert that graph G, in the graph G' where we have only edges weighted. The algorithm for converting is very simple, since we have both edges and nodes weighted, when we move from A -> B, we know that total weight to move from A to B is weight of edge(A -> B) plus weight of B itself, so lets make A -> B edge weight sum of these two weights and the weight of B zero. Than we can find shortest path from any node s to any node to in O(mlogn) where (n - number of nodes, m - number of edges)