The main idea:
Firstly, we observe that a $(1,n)$-path always exists since for any vertices $i$ and $i+1$ we have the edge $(i,i+1)$.
Consider the element with value $1$, say it is at position $i$. Similarly, the element with value $n$ at position, say $j$.
$$a_1, ..., a_i, ..., a_j, ..., a_n$$
We have the edge $(i, j)$. Additionally, there can be no edge $(x,y)$ with $x<i$ and $y>i$ or $x < j$ and $y>j$. Therefore, the shortest path must take the edge $(i,j)$, and we can apply a divide-and-conquer strategy on the sub-arrays $a_1, ..., a_{i-1}$ and $a_{j+1}, ..., a_n$. This can be implemented in linear time.
No comments:
Post a Comment