Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 478D Red Green Towers - Final Answer

Valid configurations

After processing all hh levels, dp[h][j]dp[h][j] tells you: "how many ways to build the full tower using exactly jj red blocks." But not every jj is valid.

You need: jrj \le r and SjgS - j \le g. The final answer is the sum of all valid dp[h][j]dp[h][j]:

answer=0jrSjgdp[h][j](mod109+7)\text{answer} = \sum_{\substack{0 \le j \le r \\ S - j \le g}} dp[h][j] \pmod{10^9 + 7}

Iterating jj from 00 to SS and checking both constraints takes O(S)O(S) time after the DP is filled.