Problem:
Score : 400 points

Problem Statement

You have N items and a bag of strength W.
The i-th item has a weight of w_i and a value of v_i.

You will select some of the items and put them in the bag.
Here, the total weight of the selected items needs to be at most W.

Your objective is to maximize the total value of the selected items.

Constraints

1 ≤ N ≤ 100

1 ≤ W ≤ 10^9

1 ≤ w_i ≤ 10^9

For each i = 2,3,...,N, w_1 ≤ w_i ≤ w_1 + 3.

1 ≤ v_i ≤ 10^7

W, each w_i and v_i are integers.

Input

Input is given from Standard Input in the following format:

N W
w_1 v_1
w_2 v_2
:
w_N v_N

Output

Print the maximum possible total value of the selected items.

Sample Input 1

4 6
2 1
3 4
4 10
3 4

Sample Output 1

11

The first and third items should be selected.

Sample Input 2

4 6
2 1
3 7
4 10
3 6

Sample Output 2

13

The second and fourth items should be selected.

Sample Input 3

4 10
1 100
1 100
1 100
1 100

Sample Output 3

400

You can take everything.

Sample Input 4

4 1
10 100
10 100
10 100
10 100

Sample Output 4

0

You can take nothing.

Solution in Scala (2.11.7) (judge verdict: Accepted)

import java.io.{BufferedReader, InputStream, InputStreamReader}
import java.util.StringTokenizer

import scala.collection.mutable
import scala.util.Sorting
import math.{abs, max, min}

object Main {
  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N = sc.nextInt()
    val W = sc.nextInt()
    val w = Array.ofDim[Int](N + 1)
    val v = Array.ofDim[Int](N + 1)
    val w1 = sc.nextInt()
    v(1) = sc.nextInt()
    (2 to N) foreach { i =>
      w(i) = sc.nextInt() - w1
      v(i) = sc.nextInt()
    }

    val dp = Array.ofDim[Int](N + 1, N + 1, 3 * N + 1)
    for {
      i <- 1 to N
      j <- 0 to i  // 選んだ個数
      k <- 0 to 3 * i // w1との差
    } {
      val pre_k = k - w(i)
      dp(i)(j)(k) =
        if (j >= 1 && pre_k >= 0) max(dp(i - 1)(j - 1)(pre_k) + v(i), dp(i -1)(j)(k))
        else dp(i -1)(j)(k)
    }

    val ans = (for {
      j <- 0 to N
      k <- 0 to 3 * N
      if j.toLong * w1 + k <= W
    } yield dp(N)(j)(k)).max
    println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
  }



  private class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = null

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next.toInt
    def nextLong(): Long = next.toLong
    def nextChar(): Char = next.charAt(0)
  }

}