状态压缩后的方案
const readline = require('readline').createInterface({ input: process.stdin });
let n, V, v = [0], w = [0], cc = 0, idx = 0;
const read = line => line.split(' ').map(Number);
readline.on('line', line => {
if (cc === 0) {
[n, V] = read(line);
cc++;
return;
}
if (cc) {
const [vt, wt] = read(line);
v.push(vt);
w.push(wt);
idx++;
if (idx === n) {
console.log(resolve(v, w, n, V));
}
}
});
function resolve(v, w, n, V) {
const f = new Array(V + 1).fill(0);
for (let i = 1; i<= n; i++) {
for (let j = V; j >= 0; j--) {
if (j >= v[i]) {
f[j] = Math.max(f[j], f[j - v[i]] + w[i]);
}
}
}
return f[V];
}
原始版本
const readline = require('readline').createInterface({ input: process.stdin });
let n, V, v = [0], w = [0], cc = 0, idx = 0;
const read = line => line.split(' ').map(Number);
readline.on('line', line => {
if (cc === 0) {
[n, V] = read(line);
cc++;
return;
}
if (cc) {
const [vt, wt] = read(line);
v.push(vt);
w.push(wt);
idx++;
if (idx === n) {
console.log(resolve(v, w, n, V));
}
}
});
function resolve(v, w, n, V) {
const f = [];
for (let i = 0; i <= n; i++) {
f[i] = new Array(V + 1).fill(0);
}
for (let i = 1; i<= n; i++) {
for (let j = 0; j <= V; j++) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) {
f[i][j] = Math.max(f[i][j], f[i - 1][j - v[i]] + w[i]);
}
}
}
return f[n][V];
}