From 69bee02cf12f11cf33fbc1f86b6ae2132dde1afb Mon Sep 17 00:00:00 2001 From: aPurpleBerry <2454196228@qq.com> Date: Sun, 5 Jan 2025 15:57:57 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E8=83=8C=E5=8C=85?= =?UTF-8?q?=E9=97=AE=E9=A2=98=E7=90=86=E8=AE=BA=E5=9F=BA=E7=A1=80=E5=AE=8C?= =?UTF-8?q?=E5=85=A8=E8=83=8C=E5=8C=85.md=20JavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../背包问题理论基础完全背包.md | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/problems/背包问题理论基础完全背包.md b/problems/背包问题理论基础完全背包.md index 0cc6e915..ea658f7e 100644 --- a/problems/背包问题理论基础完全背包.md +++ b/problems/背包问题理论基础完全背包.md @@ -316,7 +316,51 @@ print(knapsack(n, bag_weight, weight, value)) ### JavaScript +```js +const readline = require('readline').createInterface({ + input: process.stdin, + output: process.stdout +}); +let input = []; +readline.on('line', (line) => { + input.push(line.trim()); +}); + +readline.on('close', () => { + // 第一行解析 n 和 v + const [n, bagweight] = input[0].split(' ').map(Number); + + /// 剩余 n 行解析重量和价值 + const weight = []; + const value = []; + for (let i = 1; i <= n; i++) { + const [wi, vi] = input[i].split(' ').map(Number); + weight.push(wi); + value.push(vi); + } + + + let dp = Array.from({ length: n }, () => Array(bagweight + 1).fill(0)); + + for (let j = weight[0]; j <= bagweight; j++) { + dp[0][j] = dp[0][j-weight[0]] + value[0]; + } + + for (let i = 1; i < n; i++) { + for (let j = 0; j <= bagweight; j++) { + if (j < weight[i]) { + dp[i][j] = dp[i - 1][j]; + } else { + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - weight[i]] + value[i]); + } + } + } + + console.log(dp[n - 1][bagweight]); +}); + +```