All problems

Problem 959

Filling Bookcase Shelves

Medium · 20 pts · Array, Dynamic Programming

Problem

Books must be placed on shelves in the given order. Book i has a thickness and a height. Each shelf holds a group of consecutive books whose total thickness is at most SHELFWIDTH, and the height of a shelf is the height of its tallest book. Minimise the total height of the bookcase. Let best[i] be the answer for the first i books: try every possible last shelf, made of the books from j to i - 1.

Input

The first line contains N and SHELFWIDTH. Each of the next N lines contains a book's thickness and height.

Output

Print the minimum total height.

Constraints

1 <= N <= 1000; 1 <= thickness <= SHELFWIDTH <= 1000; 1 <= height <= 1000

Example input

7 4
1 1
2 3
2 3
1 1
1 1
1 1
1 2

Example output

6

Explanation

With books (1,1), (2,3), (2,3), (1,1), (1,1), (1,1), (1,2) and width 4, the shelves [1,1], [2,3 2,3] and [1,1 1,1 1,1 1,2] have heights 1, 3 and 2, a total of 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Maximum Alternating Subsequence Sum Next: Minimum Score Triangulation of Polygon