This page is still under construction.

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

Bookshelf

Interview

Time limit1sMemory limit128 MB

Summary
Partition the books in order into shelves whose widths sum to at most L, minimizing the total of each shelf's maximum height.
Level

Medium5 of 10

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

Problem

When Farmer John isn't milking cows, stacking haybales, lining up his cows, or building fences, he enjoys sitting down with a good book. Over the years he has collected NN books (1≤N≤2 0001 \le N \le 2\,000), and he wants to build a new set of bookshelves to hold them all.

Each book ii has a width WiW_i and a height HiH_i. The books must be placed onto the shelves in the given order: the first shelf holds books 1…k1 \dots k for some kk, the second shelf starts with book k+1k+1, and so on. The total width of the books on any single shelf may be at most LL (1≤L≤1091 \le L \le 10^9). The height of a shelf equals the height of the tallest book on it, and because the shelves are stacked vertically, the height of the whole bookcase is the sum of the heights of all the shelves.

Compute the minimum possible height of the entire bookcase.

Input

  • Line 1: two space-separated integers NN and LL.
  • Lines 2 to N+1N+1: line i+1i+1 contains two space-separated integers, the height HiH_i and the width WiW_i of book ii (1≤Hi≤1061 \le H_i \le 10^6, 1≤Wi≤L1 \le W_i \le L).

Output

  • Print the minimum possible total height of the bookcase on a single line.

Hint

Input Details

There are 5 books, and each shelf may hold books whose total width is at most 1010.

Output Details

The books are placed on 3 shelves: the first holds only book 1 (height 5, width 7), the second holds books 2…42 \dots 4 (height 13, total width 9), and the third holds book 5 (height 3, width 8).

Examples3

  1. Example 1

    Input
    5 10
    5 7
    9 2
    8 5
    13 2
    3 8
    
    Expected output
    21
    
  2. Example 2

    Input
    1 1000000000
    1000000 5
    
    Expected output
    1000000
    
  3. Example 3

    Input
    4 20
    7 5
    7 5
    7 5
    7 5
    
    Expected output
    7