AcWing 9. 分组背包问题--(Javascript)
原题链接
中等
作者:
cp777
,
2021-03-04 21:22:20
,
所有人可见
,
阅读 323
const N = 110;
let v = [];
let w = [];
for (let i = 0; i < N; i++) {
v[i] = new Int32Array(N);
w[i] = new Int32Array(N);
}
let s = new Int32Array(N);
let f = new Int32Array(N);
let n = 0;
let cnt = 1; //第几组
let buf = '';
let flag = true;
let goods_cnt = 0; //每组商品录入个数
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
m = getInputNums(line)[1];
} else if (cnt <= n) {
if (flag) {
s[cnt] = getInputNums(line)[0]; //每组物品数
flag = false;
} else {
goods_cnt++;
let a = getInputNums(line)[0];
let b = getInputNums(line)[1];
v[cnt][goods_cnt] = a;
w[cnt][goods_cnt] = b;
if (goods_cnt === s[cnt]) {
flag = true;
cnt++;
goods_cnt = 0;
}
if (cnt === n + 1) {
for (let i = 1; i <= n; i++) {
for (let j = m; j >= 0; j--) {
for (let k = 1; k <= s[i]; k++) {
if (v[i][k] <= j) f[j] = Math.max(f[j], f[j - v[i][k]] + w[i][k])
}
}
}
console.log(f[m]);
}
}
}
});
});