### toxic_hack's blog

By toxic_hack, history, 13 months ago, I have been trying to solve (Kth problem in the pdf) this problem for a couple of days. I find this problem very hard and the DP states and transitions are too confusing for me. I don't know how to go about thinking these types of problems :( Can someone please explain how to approach this problem? It will be very helpful.  Comments (2)
 » 13 months ago, # | ← Rev. 2 →   I finally managed to figure out the solution. I will just write it down so that it will be helpful to someone. SpoilerWe will try to use two dp states. Let $f(n)$ denote the number of ways that the salesman can start from the leftmost column and finish wherever he wants. Let $t(n)$ denote number of ways that the salesman start somewhere in between and finishes the left part first and then proceeds towards the right part.We should directly be able to get the formula for these states.$f(n) = 2*f(n-1) + 4*f(n-2) + 2^n$ Spoiler$2*f(n-1)$ comes from the fact that the salesman can start anywhere in the first column and then connect it to the $n-1$ previous columns.$4*f(n-2)$ denotes the zig-zag type starting from the first column that we missed previously.$2^n$ denotes the ways that start with the first column and end at the first column.$t(n) = 2*t(n-1) + 4*f(n-2)$ Spoiler$2*t(n-1)$ is self explanatory. That just tells that for all the ways in $t(n-1)$ when the sales person comes to $n-1^{th}$ column just come to $n^{th}$ column in $2$ ways.$4*f(n-2)$: Now since $n-1^{th}$ column has become a middle column for the $n^{th}$ column we count their ways too. It's just casework to figure out why the coefficient is $4$.Now the final answer is: $2*f(n) + 2*t(n)$.Since all of these are linear recurrences they can be solved using matrix exponentiation. I hope this will help someone.
•  » » Ty, that was very helpful