This page is still under construction.

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

Ploughing

Time limit1sMemory limit128 MB

Summary
Given an m by n grid of tile difficulties, repeatedly remove a full strip of width 1 from any edge as long as the strip sum is at most k, and minimize the number of strips that remove every tile.
Level

Hard8 of 10

Topics
Dynamic programming, Two pointers, Prefix sum, Binary search
Solved
No attempts yet

Problem

Byteasar the farmer wants to plough his rectangular field. The field is ploughed one slice at a time. Each slice is a full strip of width 11 taken from one of the four edges of the not-yet-ploughed region, and after every slice the remaining region is still a rectangle. This repeats until the whole field is ploughed.

Byteasar has only one weak horse. Once the horse starts a slice, it cannot stop until that slice is finished; it may rest only between slices. Each tile has a non-negative integer ploughing difficulty. The field consists of m×nm \times n unit tiles, and the tile in column ii, row jj (where 1≤i≤m1 \le i \le m and 1≤j≤n1 \le j \le n) has difficulty ti,jt_{i,j}. For any slice, the sum of the difficulties of its tiles must not exceed a constant kk; otherwise the horse collapses from exhaustion, so every slice must have a difficulty sum of at most kk.

Before each slice Byteasar chooses which edge to plough so that no slice exceeds kk, and he wants to plough the entire field using as few slices as possible.

Write a program that reads kk, mm, nn and the difficulty coefficients, and outputs the minimum number of slices needed to plough the whole field.

Input

The first line contains three positive integers kk, mm, and nn, separated by single spaces (1≤k≤2×1081 \le k \le 2 \times 10^{8}, 1≤m,n≤20001 \le m, n \le 2000). Each of the next nn lines gives the ploughing-difficulty coefficients: line j+1j+1 contains t1,j,t2,j,…,tm,jt_{1,j}, t_{2,j}, \dots, t_{m,j}, separated by single spaces (0≤ti,j≤1050 \le t_{i,j} \le 10^{5}).

Output

Output a single integer: the minimum number of slices needed to plough the whole field while satisfying the rule above. It is guaranteed that the field can always be ploughed.

Hint

The illustration above shows one optimal way to plough the field from the example.

Examples1

  1. Example 1

    Input
    12 6 4
    6 0 4 8 0 5
    0 4 5 4 6 0
    0 5 6 5 6 0
    5 4 0 0 5 4
    
    Expected output
    8