Problem:
0-1 Knapsack Problem

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 1000

1 ≤ wi ≤ 1000

1 ≤ W ≤ 10000

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9

Solution in PHP (judge verdict: Accepted)

<?php

class Scanner
{
    private $arr = [];
    private $count = 0;
    private $pointer = 0;

    /**
     * @return mixed
     */
    public function next() {
        if ($this->pointer >= $this->count) {
            $str = trim(fgets(STDIN));
            $this->arr = explode(' ', $str);
            $this->count = count($this->arr);
            $this->pointer = 0;
        }
        $result = $this->arr[$this->pointer];
        $this->pointer++;
        return $result;
    }

    /**
     * @return bool
     */
    public function hasNext() {
        return $this->pointer < $this->count;
    }

    /**
     * @return int
     */
    public function nextInt() {
        return (int)$this->next();
    }

    /**
     * @return float
     */
    public function nextDouble() {
        return (double)$this->next();
    }
}

// 初期化
$sc = new Scanner();
$N = $sc->nextInt();
$W = $sc->nextInt();
$v = array();
$w = array();
for ($i = 1; $i <= $N; $i++) {
    $v[$i]= $sc->nextInt();
    $w[$i]= $sc->nextInt();
}
unset($sc);

$dp = array();
$dp[0] = array_fill(0, $W+1, 0);

for ($i = 1; $i <= $N; $i++) {
    for ($j = 0; $j <= $W; $j++) {
        if ($j >= $w[$i]) {
            // 取れる場合 前のやつと比較する (左が取る場合、右が取らない場合)
            $dp[$i][$j] = max($dp[$i-1][$j - $w[$i]] + $v[$i], $dp[$i-1][$j]);
        } else {
            // 取れない場合
            $dp[$i][$j] = $dp[$i-1][$j];
        }
    }
    // メモリ足りないのでもういらない分は解放
    if ($i >= 2) {
        unset($dp[$i-2]);
    }
}
echo $dp[$N][$W] . "\n";