PrevNext
Rare
 0/15

Additional DP Optimizations and Techniques

Author: Andi Qu

Additional dynamic programming techniques and optimizations like Knuth's optimization.

Knuth's Optimization

Tutorials

Resources
Jeffrey Xiao
GCP
GFG

Good explanation + Proof of correctness

Knuth's optimization is a special case of Range DP. In general, it is used to solve DP problems with transitions of the form

dp[i][j]=cost[i][j]+minik<j(dp[i][k]+dp[k+1][j]).\texttt{dp}[i][j] = \texttt{cost}[i][j] + \min_{i\leq k<j}(\texttt{dp}[i][k] + \texttt{dp}[k+1][j]).

Further, the cost function must satisfy the following conditions for all abcda\leq b\leq c \leq d:

  1. cost[b][c]cost[a][d]\texttt{cost}[b][c] \leq \texttt{cost}[a][d]
  2. cost[a][c]+cost[b][d]cost[a][d]+cost[b][c]\texttt{cost}[a][c] + \texttt{cost}[b][d] \leq \texttt{cost}[a][d] + \texttt{cost}[b][c] (the quadrangle inequality)

Define opt[i][j]\texttt{opt}[i][j] be the index for which dp[i][k]+dp[k+1][j]\texttt{dp}[i][k] + \texttt{dp}[k+1][j] takes on its minimum value, or equivalently,

opt[i][j]=arg minik<j(dp[i][k]+dp[k+1][j]).\texttt{opt}[i][j] = \argmin_{i\leq k<j}(dp[i][k] + dp[k+1][j]).

If more than one such index exists, then take the minimum (or the maximum, doesn't matter). Then, assuming conditions on the dp transition and the cost function to be satisfied, we can show that opt\texttt{opt} satisfies

opt[i][j1]opt[i][j]opt[i+1][j].\texttt{opt}[i][j-1] \leq \texttt{opt}[i][j] \leq \texttt{opt}[i+1][j].

The proof of correctness for this claim is in the resources above.

The structure of the code is identical to that of Range DP, with the exception of maintaining the opt\texttt{opt} array. To calculate dp[i][j]\texttt{dp}[i][j] and opt[i][j]\texttt{opt}[i][j], it is only necessary to check values of kk between opt[i][j1]\texttt{opt}[i][j-1] and opt[i+1][j]\texttt{opt}[i+1][j]. Because of the monotonicity of opt\texttt{opt}, the time complexity of the final algorithm can be shown to be O(N2)\mathcal{O}(N^2).

Knuth's Optimization Problems

StatusSourceProblem NameDifficultyTags
CFEasy
SPOJNormal
onlinejudge.orgNormal
onlinejudge.orgHard

Connected-Component DP

Resources
CF

Miscellaneous techniques

Connected-Component DP Problems

This section is not complete.

Any help would be appreciated! Just submit a Pull Request on GitHub.

Make Permutations II a focus problem, move analysis to module.

StatusSourceProblem NameDifficultyTags
CSESEasy
CFEasy
CEOINormal
CFNormal
JOINormal
CFNormal

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext