Problem : https://codeforces.net/contest/1288/problem/C
My solution: https://codeforces.net/contest/1288/submission/68821660
Can anyone tell while I calculate dp[pos][i][j], I am using O(n*n) to calculate for each pair. Can I optimize by using some precalculated sum array, as we do in 1D case to get the sum for a particular range in an array?
In my code, I have written this, //to calculate dp[pos][i][j] //using dp[pos — 1][previ][prevj]
How can I do this in O(1) to fit in timelimit?
I am thinking about this optimization for a long time, but I got to nowhere.
It would be great if there is any way to do it.
Thank you :)
Have a great day!
Yes, you can use precalculated sum for matrix.
Let be $$$p_{ij}$$$ sum of all elements whose indices less than $$$i$$$ and $$$j$$$. This can be calculated as follows:
Sum of all elements specified by indices $$${x_1, y_1}$$$ and $$${x_2, y_2}$$$ (0-indexing) can be calculated:
In problem you can calculate sum elements use only array dp.
Thanks a lot Fortin!
Sometimes we can remove some loops by changing our transitions.
You can think that we will change $$$i$$$ and $$$j$$$ in all possible ways before using dp of $$$pos-1$$$.
$$$dp[pos][i][j] = dp[pos-1][i][j] + dp[pos][i+1][j] + dp[pos][i][j-1]$$$
But there is a problem with this. The state $$$[pos][i+1][j-1]$$$ can be reached in two different ways($$$[pos][i+1][j] => [pos][i+1][j-1]$$$ and $$$[pos][i][j-1]=>[pos][i+1][j-1]$$$) and it is overcounted. However, it is always two ways so we can easily remove one.
$$$dp[pos][i][j] = dp[pos-1][i][j] + dp[pos][i+1][j] + dp[pos][i][j-1] - dp[pos][i+1][j-1]$$$
And the answer is just $$$dp[m][1][n]$$$.
It's possible improve it further by normalizing $$$i$$$ and $$$j$$$ so that always $$$i = 1$$$. Now that $$$i$$$ is constant, it can be removed from our states. The dp becomes:
$$$dp[pos][j] = dp[pos-1][j] + dp[pos][j-1] + dp[pos][j-1] - dp[pos][j-2]$$$
And the answer is $$$dp[m][n]$$$.