Partition DP: try every split point

Video lessonComing soon

1 A stick, three marks and an order

A carpenter has a stick 10 long, with marks at 4, 5 and 6. He must cut at every mark. A cut splits one piece into two, and it costs the length of that piece at the moment he cuts it. This is Minimum Cost to Cut a Stick.

10045610
The stick, 10 long, with three marks to cut

The first cut always costs 10, because the whole stick is still one piece. After that, the order changes the price. Cutting at 6 first leaves short pieces for the other two cuts:

Cutting at 6, then 4, then 5
10045610cut
Cut at 6 on the whole stick: costs 10

Cutting at the middle mark first looks sensible, but it costs 10 + 5 + 5 = 20. Here are all six orders:

OrderEach cut costsTotal
4, 5, 610 + 6 + 521
4, 6, 510 + 6 + 218
5, 4, 610 + 5 + 520
5, 6, 410 + 5 + 520
6, 4, 510 + 6 + 218
6, 5, 410 + 6 + 521

Three marks give 6 orders. Twenty marks give about 2 × 10¹⁸, so we cannot try every order. This lesson finds the cheapest one without listing them.

2 The first cut splits the problem

Look only at the first cut. Cutting at 6 leaves two pieces, 0 to 6 and 6 to 10. From then on, a cut on one piece never changes the length of the other. Each piece needs its own cheapest order, and it does not matter which piece we work on first.

So the cheapest plan that starts at 6 costs 10, plus the cheapest way to cut 0 to 6, plus the cheapest way to cut 6 to 10. We do not know the best first cut, so we try every mark as the first cut and keep the smallest total. This is partition DP, also called interval DP. A range is solved by trying every split point, and each split leaves two smaller ranges of the same kind.

This covers every order. Any order starts with some first cut. The rest of it cuts the left piece and the right piece, so it costs at least the cheapest way for each. The plan that splits there and then cuts both pieces the cheapest way is never worse.

To name the pieces, we add the stick's two ends to the marks and sort them. A piece always runs from one mark to another, so two indexes name it.

00415263104
marks: the two ends and the three cuts, sorted

The state is dp[i][j]: the cheapest way to make every cut that lies strictly between mark i and mark j. The whole stick is dp[0][4].

PartStick cutting
Statedp[i][j], the piece from mark i to mark j
Transitiontry every mark k between i and j as the first cut
Base casesdp[i][i + 1] = 0, since no mark lies inside
dp[i][j] = min(dp[i][k] + dp[k][j]) + marks[j] − marks[i]

The min runs over every k with i < k < j. The last part is the first cut's cost, the length of the piece. It is the same for every k, so it sits outside the min.

3 Fill short ranges first

dp[i][k] and dp[k][j] are both shorter pieces than dp[i][j]. In the table, dp[i][k] sits in the same row to the left, and dp[k][j] sits in the same column below. Here are the cells dp[0][4] reads:

012340–?1––2–––3––––4–––––
Row i, column j. The ? cell reads its row to the left and its column below

So a loop that fills row 0 first fails, because row 0 needs rows 1 to 3. Instead we measure a piece by its span, j − i, the number of gaps between its two marks. Every cell reads only cells of a smaller span. So we fill the table one span at a time, from span 1 up. In the table, each span is one diagonal:

Filling dp by span
00415263104
marks
012340–01––02–––03––––04–––––
Span 1: no mark inside, so 0

Take dp[0][3] in step 3. It is the piece 0 to 6, with marks 4 and 5 inside. Cutting at 4 first leaves dp[1][3] = 2, and cutting at 5 first leaves dp[0][2] = 5. The smaller is 2, and the cut on a piece 6 long adds 6, so dp[0][3] = 8.

4 One cell in full

The last cell, dp[0][4], is the whole stick. The steps below try each mark as the first cut. The stick shows the two pieces each cut leaves, and the table shows the two cells they read:

Every first cut for dp[0][4]
dp[0][1] = 0dp[1][4] = 8045610first cut
012340–058?1––0282–––053––––04–––––
k = 1, cut at 4: 0 + 8 = 8
kFirst cut atdp[0][k]dp[k][4]Sum
14088
255510
36808

The smallest sum is 8, and the first cut costs 10, so dp[0][4] = 18. Cuts at 4 and at 6 tie, which matches the two orders that cost 18 in section 1. The middle cut leaves two pieces that each still need a cut of 5. An end cut leaves one piece with nothing to cut.

5 The code, and the memo version

The code builds marks, then fills dp one span at a time. For each cell, it tries every k from i + 1 to j − 1, keeps the smallest sum in best, and adds the piece's length.

Every tab returns 18 for a stick of 10 with cuts [4, 5, 6], and also for [6, 4, 5], since the code sorts the marks. A stick 10⁹ long, cut at every eighth, returns 3000000000.

The memo version needs no fill order. It starts at the whole stick and asks for smaller pieces only when it needs them. For partition DP, it is often the easier one to write, because the recursion is the formula as it stands:

cheapest(i, j)
    if j - i < 2
        return 0
    if memo[i][j] is filled
        return memo[i][j]
    best = infinity
    for k from i + 1 to j - 1
        left = cheapest(i, k)
        right = cheapest(k, j)
        best = min(best, left + right)
    memo[i][j] = best + marks[j] - marks[i]
    return memo[i][j]

It calculates the same cells as the table, so it costs the same. Each call is on a shorter piece than its caller, so the recursion goes at most m levels deep, where m is the number of marks.

6 Cost

Let m be the number of marks: the cuts plus the two ends. The table has m² cells, and each cell tries up to m first cuts. So the time is O(m³), and the table takes O(m²) space.

The stick's length does not appear in either. It is only a number we add, so a stick 10⁹ long costs no more than a stick 10 long.

CutsSteps, aboutVerdict
50010⁸fits
10⁴10¹²TLE

At 500 cuts, the table holds about 2.5 × 10⁵ cells. Short pieces have only a few marks to try, so the real step count is a few times lower than 10⁸.

7 Mistakes and edge cases

  • Filling row by row from the top. dp[0][3] reads dp[1][3] before row 1 is filled, and gets 0 for it. On our stick, the code returns 10 instead of 18.
  • The wrong range for k. k runs from i + 1 to j − 1. Letting k be i or j means cutting at the piece's own end, which is no cut. It reads dp[i][j] itself, still 0, and our stick comes out at 10.
  • Forgetting the cut's cost. Without marks[j] - marks[i], every cell is a sum of zeros, and the answer is 0.
  • Not sorting the cuts. The cuts can come in any order. Unsorted, [6, 4, 5] gives marks [0, 6, 4, 5, 10], pieces of negative length, and an answer of 13.
  • A table over the stick's positions. A table with one row per position needs n² cells, 10¹⁸ at n = 10⁹. Index the table by marks.
  • Overflow. At n = 10⁹, each round of cuts can cost 10⁹ in all, and 3 × 10⁹ is past the 32-bit limit of about 2 × 10⁹. Keep the costs in long long.

8 Other problems with this shape

The sign is a choice of where to split a range, where each side becomes a smaller problem of the same kind. Before any code, answer three questions: what the range is, what the split point chooses, and what the split costs.

Burst Balloons needs one twist. Each balloon pays its value times its two current neighbours. If we choose the balloon burst first, its two neighbours become next to each other, so the two sides are not independent. In [2, 4, 3], bursting 4 first pays 2 × 4 × 3 = 24, and then 2's neighbour is 3, not 4. The fix is to choose the balloon burst last in the range. While it stands, it walls the two sides off from each other, as the stick's first cut does. When it finally bursts, its neighbours are the two balloons just outside the range, so its pay is known. Choosing "first" here is the most common mistake.

The others in this section, in one line each:

  • Matrix chain multiplication. The split is the last multiplication, which joins matrices i to k with k + 1 to j. It costs rows of i × columns of k × columns of j.
  • Ways to evaluate a boolean expression to true. The split is the operator applied last. Each side counts its ways to be true and its ways to be false.
  • Palindrome Partitioning II and Partition Array for Maximum Sum. The pieces lie side by side from the left, so only the last piece's start matters. The state shrinks to one index, the end of a prefix, and each state tries every start for its last piece.

The next lesson, on bitmask DP, uses a set of chosen items as the state instead of a range.

The habit to keep: for a range problem, ask which choice splits it into two parts that never affect each other. Try every split point, fill the table by span, and add the split's own cost.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.