JOISC 2020 Building 4: How to prove the interval DP property?

Revision en1, by avighnakc, 2025-05-22 11:07:36

I've been working on this problem from JOISC 2020:

JOI20_building4 — oj.uz link

Problem summary

You're given two arrays $$$a$$$ and $$$b$$$ of length $$$2n$$$. You have to pick exactly $$$n$$$ elements from each array to form a sequence of $$$2n$$$ total elements (alternating picks between the two arrays), such that the resulting sequence is non-decreasing. If possible, also print such a sequence using 'A' and 'B' to indicate from which array each element was chosen.

Dynamic programming

The following dynamic programming solution is fairly obvious:

$$$\text{dp}[i][j][k]$$$ denotes whether it's possible to get an increasing subsequence from the first $$$i$$$ elements picking exactly $$$j$$$ elements from $$$a$$$, with $$$k$$$ being $$$1$$$ meaning you're forced to pick $$$a[i]$$$ and $$$k$$$ being $$$0$$$ meaning you're forced to pick $$$b[i]$$$.

These 'forcing' condition allow us to check monotonicity easily, because now looking at a previous dynamic programming state to check whether we're $$$\ge$$$ than it will be easy. Transitions are:

$$$\text{dp}[i][j][k]={\text{dp}[i-1][j-k][1]\,\text{and}\, a[i-1]\le \text{arr}[k][i]} \,\text{or}\,{\text{dp}[i-1][j-k][0]\,\text{and}\, b[i-1]\le \text{arr}[k][i]}$$$

where $$$\text{arr}[0] = b$$$ and $$$\text{arr}[1] = a$$$.

  dp[0][0][0] = dp[0][0][1] = true;
  int *arr[] = {b, a};
  for (int i = 1; i <= n << 1; ++i) {
    for (int j = 0; j <= n; ++j) {
      for (int k = 0; k < 2; ++k) {
        if (j - k >= 0) {
          dp[i][j][k] = (dp[i - 1][j - k][1] && a[i - 1] <= arr[k][i]) || (dp[i - 1][j - k][0] && b[i - 1] <= arr[k][i]);
        }
      }
    }
  }

Full solution

Okay, so this is where the editorial mentions something

Tags dp, ojuz, joisc2020, proofs

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en10 English avighnakc 2025-05-22 13:16:32 4
en9 English avighnakc 2025-05-22 13:15:57 6 Tiny change: 'en from:\n- $a$ if' -> 'en from:\n\n- $a$ if'
en8 English avighnakc 2025-05-22 11:38:30 4
en7 English avighnakc 2025-05-22 11:36:16 6 Tiny change: ' range $(j1, j2)$, $dp[i' -> ' range $(j_1, j_2)$, $dp[i'
en6 English avighnakc 2025-05-22 11:35:34 33
en5 English avighnakc 2025-05-22 11:28:05 4 (published)
en4 English avighnakc 2025-05-22 11:27:04 5 Tiny change: 'ke the $1$s form a c' -> 'ke the $1$'s form a c'
en3 English avighnakc 2025-05-22 11:26:03 6 Tiny change: 'uts\n\n```\nSample 1' -> 'uts\n\n```md\nSample 1'
en2 English avighnakc 2025-05-22 11:25:37 1939 Tiny change: 'with the $\i^\text{th' -> 'with the $i^\text{th'
en1 English avighnakc 2025-05-22 11:07:36 1799 Initial revision (saved to drafts)