Problem:
0-1 Knapsack Problem II

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 N 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 ≤ 100

1 ≤ wi ≤ 10,000,000

1 ≤ W ≤ 1,000,000,000

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 C++14 (judge verdict: Memory Limit Exceeded)

#include <iostream>
#include <vector>

#define FOR(i,n) for(int i=0;i<n;i++)
#define FORI(i,z,n) for(int i=z;i<n;i++)

using namespace std;

struct Obj {int weight; int value;};

int main () {
    int N, W;
    cin >> N >> W;

    vector<Obj> objects(N);
    FOR(i,N) {
        int v, w;
        cin >> v >> w;
        objects[i] = Obj{w, v};
    }

    vector<int> oldCol(W+1, 0), newCol(W+1, 0);

    FOR(i, N) {
        newCol[0] = 0;
        Obj o = objects[i];
        FORI(j, 1, W+1) {
            int m = 0;
            m = max(m, newCol[j-1]);
            m = max(m, oldCol[j]);
            if (j >= o.weight)
                m = max(m, oldCol[j-o.weight] + o.value);
            newCol[j] = m;
        }

        oldCol = newCol;
    }

    cout << oldCol[W] << endl;
}