This page is still under construction.

Parts of this page are still being built. What you see may change.

Raisins

Interview

Time limit3sMemory limit128 MB

Summary
Split an N by M chocolate bar into unit cells by straight cuts; each cut costs the raisins in the piece, and the goal is to minimize the total payment.
Level

Medium6 of 10

Topics
Dynamic programming, Prefix sum, Divide and conquer, Implementation
Solved
No attempts yet

Problem

Bonny, a famous chocolate maker in Plovdiv, has made an N×MN \times M raisin chocolate bar arranged as a grid with MM columns and NN rows. Every 1×11 \times 1 cell contains at least one raisin, and no raisin spans more than one cell.

Initially the chocolate is a single large block, and Bonny must split it into all N×MN \times M of its 1×11 \times 1 pieces. The greedy Peter does the cutting. In one move Peter takes a single rectangular piece and cuts it into two along one straight horizontal or vertical line, demanding a reward for each cut.

Having no money, Bonny pays Peter in raisins. Peter's rule is: each time a rectangular piece is cut into two, he is paid the total number of raisins contained in that piece just before the cut. Bonny may choose which piece to cut and where to cut it.

Given the number of raisins in every cell, find the minimum total number of raisins Bonny must pay to split the whole bar into 1×11 \times 1 pieces.

Input

  • The first line contains the chocolate's dimensions NN and MM.
  • Each of the next NN lines contains MM integers RijR_{ij}, the number of raisins in the cell at row ii, column jj.
  • 1≤N,M≤501 \le N, M \le 50
  • 1≤Rij≤10001 \le R_{ij} \le 1000

Output

Print, on a single line, the minimum number of raisins Bonny must pay.

Hint

This can be solved with interval dynamic programming over sub-rectangles. The cost of one cut on a rectangular piece is the total number of raisins inside it, and the two resulting pieces are then split independently. So, computing the minimum cost to fully break each rectangle into 1×11 \times 1 cells from the smallest rectangles upward yields the overall answer.

Examples3

  1. Example 1

    Input
    2 3
    2 7 5
    1 9 5
    
    Expected output
    77
    
  2. Example 2

    Input
    1 1
    5
    
    Expected output
    0
    
  3. Example 3

    Input
    1 2
    3 4
    
    Expected output
    7