David Berger's answer is correct if you do not mean a simple path where each vertex can meet no more than once, in which case Bellman-Ford will not give the longest path. Since you are saying that the weights are positive, it is not possible for the longest path to exist when the graph has a cycle (reachable from the source) unless you mean a simple path. The longest easy-path problem is NP-complete. See Wikipedia .
So let's say you mean a directed acyclic graph (DAG). In linear time, you can calculate the longest path to each vertex v from the initial vertex s, given that you know the longest path from s β * u for each u, where u-> v directly. This is easy - you can do the first depth search on your oriented graph and calculate the longest path for the vertices in the reverse order of their visits. You can also detect the trailing edges of the entire DFS using 3-color marking (open but not finished vertices are gray). See Wikipedia for more details. The longest / shortest path to the DAG is sometimes called the Viterbi algorithm (although it was specified taking into account a specific type of DAG).
At first I tried to use a linear dynamic programming solution. If you have cycles, then Bellman-Ford still will not solve your problem.
source share