SHELF - Book Shelves

no tags 

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 N books (1 ≤ N ≤ 100,000), and he wants to build a new set of bookshelves to hold them all.

Each book i has a width W(i) and height H(i). The books need to be added to a set of shelves in order; for example, the first shelf should contain books 1...k for some k, the second shelf should start with book k+1, and so on. Each shelf can have a total width of at most L (1 ≤ L ≤ 1,000,000,000). The height of a shelf is equal to the height of the tallest book on that shelf, and the height of the entire set of bookshelves is the sum of the heights of all the individual shelves, since they are all stacked vertically.

Please help FJ compute the minimum possible height for the entire set of bookshelves.

Input

  • Line 1: Two space-separated integers: N and L.
  • Lines 2..1+N: Line i+1 contains two space-separated integers: H(i) and W(i). (1 ≤ H(i) ≤ 1,000,000; 1 ≤ W(i) ≤ L).

Output

  • Line 1: The minimum possible total height for the set of bookshelves.

Sample

Input
5 10
5 7 
9 2 
8 5 
13 2 
3 8

Output
21

Explanation

There are 5 books. Each shelf can have total width at most 10.

There are 3 shelves, the first containing just book 1 (height 5, width 7), the second containing books 2, 3 and 4 (height 13, width 9), and the third containing book 5 (height 3, width 8).


hide comments
:D: 2012-05-01 13:37:23

As the N limit suggests, it's an O(N*log(N)) problem (or lower). If you're trying a little naive O(N^2), it will probably not cut it.

RE: you're right, but tutorial version, has time limit of 30(!) secs, so n^2 should pass, plus thinking of an n^2 solution is sort of a practice for newbies.

RE RE: Ok, I was NOT opting against tutorial version. Only giving a hint to cegprakash.

Last edit: 2012-05-02 15:10:26
cegprakash: 2012-05-01 13:37:23

could u plz add a copy of this problem in tutorial with more time limit
RE: Added http://www.spoj.pl/problems/SHLF/

Last edit: 2012-04-28 15:38:27

Added by:Ikhaduri
Date:2012-04-25
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:Usaco open 2012