I know that the longest path problem is NP-hard for a general graph. However, I am considering a particular kind of graph, consisting of one cycle, plus one additional edge incident on each vertex of the cycle. For example, for a cycle of length 7, we have the graph:
All the edges are weighted (the weight is a real number and can be positive or negative). I want to find the largest simple path on this graph, where the size of a path is the sum of the weights of the edges on the path.
The algorithm should be linear in the size of the cycle. But any ideas are appreciated.
A longest path between two given vertices s and t in a weighted graph G is the same thing as a shortest path in a graph −G derived from G by changing every weight to its negation. Therefore, if shortest paths can be found in −G, then longest paths can also be found in G.
Since the Hamiltonian path problem is NP-hard, so is the longest path problem.
Efficient Approach: An efficient approach is to use Dynamic Programming and DFS together to find the longest path in the Graph. Let dp[i] be the length of the longest path starting from the node i. Initially all positions of dp will be 0. We can call the DFS function from every node and traverse for all its children.
This could be reduced to Maximum subarray problem and solved in linear time.
->
Necessary Kadane's algorithm modifications:
N
or more "cycle" nodes. To trim these nodes efficiently, we need a queue that can report minimum value of its elements. Push elements to this queue wherever head of the path is advanced (add leaf edge weight if non-negative), pop elements when tail of the path is trimmed, and reset the queue wherever current path is reset to empty path. This queue contains prefix lengths of (not necessarily simple) path, where minimum value gives proper position to advance tail of the path. Such a queue may be implemented either as a deque holding only non-decreasing values, or as a pair of stacks as mentioned in this answer.max(0, leaf_edge_weight)
wherever length of current path is below zero (instead of resetting it to zero as in original Kadane's algorithm).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