Asked By : sudomakeinstall2
Answered By : David Richerby
- Topologically sort the vertices.
- Set $ell(x) = 0$ for each sink $x$.
- Working back from the leaves in the topological ordering, set $ell(x) = 1 + max,{ell(y_1), dots, ell(y_k)}$ for each vertex $x$ with out-neighbours $y_1, dots, y_k$.
Note that the topological ordering guarantees that we’ve already computed $ell(y_i)$ for each out-neighbour $y_i$. When the labelling is computed, it has the property that, for every vertex $xin H$, $ell(x)$ is the length of the longest path from $x$ to a sink in $H$. Now, produce a graph $H’$ from $H$ as follows.
- Delete every edge $(x,y)$ such that $ell(x)neqell(y)+1$.
- Let $m = max,{ell(x)mid xtext{ is a source in }H}$ (this is the length of the longest path in $H$).
- Iteratively delete every source $y$ with $ell(y)<m$.
$H’$ contains exactly the vertices and edges of $H$ that appear in longest paths in $H$ (put another way, $H’$ is the union of all longest paths in $H$). In particular, every path from a source to a sink in $H’$ has length exactly $m$, which is the greatest length of any path in $H$. Now, produce a graph $G’$ from $G$ as follows.
- Delete from $G$ any component $C$ such that $h(C)notin H’$.
- Delete from $G$ any edge from component $C_1$ to component $C_2$ if there is no edge $(h(C_1),h(C_2))$ in $H’$.
Finally, let $Ssubseteq V(G’)$ be the set of all vertices whose components are sources in $H’$ and let $Tsubseteq V(G’)$ be the vertices in components that are sinks in $H’$. The $S$ $T$ paths in $G’$ are exactly the paths in $G$ that visit the maximum possible number of components. Use your favourite shortest path algorithm to find a shortest one. Thanks to Bakuriu for suggesting topological sort instead of my ad-hoc algorithm.
Best Answer from StackOverflow
Question Source : http://cs.stackexchange.com/questions/49481