朴素写法
const rl = require('readline').createInterface({ input: process.stdin });
const read = line => line.split(' ').map(Number);
let v = [0], w = [0], n, m, cc = 0, idx = 0;
rl.on('line', line => {
if (cc === 0) {
cc++;
[n, m] = read(line);
return;
}
if (cc) {
idx++;
[v[idx], w[idx]] = read(line);
if (idx === n) {
console.log(resolve(v, w, n, m));
}
}
});
function resolve(v, w, n, m) {
// const f = new Array(m + 1).fill(0);
const f = new Array(n + 1);
for (let i = 0; i <= n; i++) {
f[i] = new Array(m + 1).fill(0);
}
for (let i = 1; i <= n; i++) {
for (let j = 0; j <= m; j++) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) {
f[i][j] = Math.max(f[i - 1][j], f[i][j - v[i]] + w[i]);
}
}
}
return f[n][m];
// console.log(f[n][m]);
}
状态压缩完毕后的写法
const rl = require('readline').createInterface({ input: process.stdin });
const read = line => line.split(' ').map(Number);
let v = [0], w = [0], n, m, cc = 0, idx = 0;
rl.on('line', line => {
if (cc === 0) {
cc++;
[n, m] = read(line);
return;
}
if (cc) {
idx++;
[v[idx], w[idx]] = read(line);
if (idx === n) {
console.log(resolve(v, w, n, m));
}
}
});
function resolve(v, w, n, m) {
const f = new Array(m + 1).fill(0);
for (let i = 1; i <= n; i++) {
for (let j = v[i]; j <= m; j++) {
f[j] = Math.max(f[j], f[j - v[i]] + w[i]);
}
}
return f[m];
}