Candy Delivery

Time limit1sMemory limit512 MB

Summary
Given N candies weighing 3 g or 5 g with sweetness values and a weight limit w, choose a subset to maximize total sweetness.
Level

Medium6 of 10

Topics
Greedy, Sorting, Prefix sum, Brute force
Solved
No attempts yet

Problem

Baby Seokhwan, who loves candy, has brought home a sack containing N candies. The sack holds two kinds of candy: a small candy weighs 3 g and a large candy weighs 5 g. Clever baby Seokhwan has computed the sweetness s_i of every candy in the sack. s_i is a positive integer, and a larger s_i means a sweeter candy.

Baby Seokhwan is packing for shake! 2019 and wants to take as many sweet candies as possible to replenish sugar during the contest. But baby Seokhwan is frail and can carry at most w grams of candy in the bag. If baby Seokhwan packs candies while satisfying this condition, what is the maximum possible sum of the sweetness of the candies taken?

Input

The first line gives the number of candies N (1 ≤ N ≤ 250,000) and the weight limit w (0 ≤ w ≤ 5N).

The following N lines give the type t_i and the sweetness s_i of each candy. (ti∈{3,5}t_i \in \{3, 5\}, 1 ≤ s_i ≤ 10^9)

Output

Print the maximum sum of sweetness of candies baby Seokhwan can take while satisfying the condition.

Hint

Warning for Java/Kotlin users! Contrary to common belief, Java's built-in Arrays.sort and Kotlin's IntArray.sort() are implemented with algorithms of O(N2)O(N^2) time complexity. The test data for this problem is designed so that using those functions results in a time limit exceeded verdict, so use a different sorting function such as Collections.sort.

Examples1

  1. Example 1

    Input
    10 11
    3 10
    3 20
    3 30
    3 40
    3 50
    5 20
    5 40
    5 60
    5 80
    5 100
    
    Expected output
    190