Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69bee02

Browse files
添加 背包问题理论基础完全背包.md JavaScript版本
1 parent cf46334 commit 69bee02

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

‎problems/背包问题理论基础完全背包.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,51 @@ print(knapsack(n, bag_weight, weight, value))
316316

317317
### JavaScript
318318

319+
```js
320+
const readline = require('readline').createInterface({
321+
input: process.stdin,
322+
output: process.stdout
323+
});
324+
325+
let input = [];
326+
readline.on('line', (line) => {
327+
input.push(line.trim());
328+
});
329+
330+
readline.on('close', () => {
331+
// 第一行解析 n 和 v
332+
const [n, bagweight] = input[0].split(' ').map(Number);
333+
334+
/// 剩余 n 行解析重量和价值
335+
const weight = [];
336+
const value = [];
337+
for (let i = 1; i <= n; i++) {
338+
const [wi, vi] = input[i].split(' ').map(Number);
339+
weight.push(wi);
340+
value.push(vi);
341+
}
342+
343+
344+
let dp = Array.from({ length: n }, () => Array(bagweight + 1).fill(0));
345+
346+
for (let j = weight[0]; j <= bagweight; j++) {
347+
dp[0][j] = dp[0][j-weight[0]] + value[0];
348+
}
349+
350+
for (let i = 1; i < n; i++) {
351+
for (let j = 0; j <= bagweight; j++) {
352+
if (j < weight[i]) {
353+
dp[i][j] = dp[i - 1][j];
354+
} else {
355+
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - weight[i]] + value[i]);
356+
}
357+
}
358+
}
319359

360+
console.log(dp[n - 1][bagweight]);
361+
});
362+
363+
```
320364

321365
<p align="center">
322366
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /