Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "use strict";
- process.stdin.resume();
- process.stdin.setEncoding("utf-8");
- let inputString = "";
- let currentLine = 0;
- process.stdin.on("data", inputStdin => {
- inputString += inputStdin;
- });
- process.stdin.on("end", _ => {
- inputString = inputString
- .replace(/\s*$/, "")
- .split("\n")
- .map(str => str.replace(/\s*$/, ""));
- main();
- });
- function readLine() {
- return inputString[currentLine++];
- }
- function main() {
- // number
- const n = parseInt(readLine());
- // weight1,value1 weight2,value2 ...
- const wv = readLine()
- .split(" ")
- .map(pair => pair.split(",").map(Number));
- // expected weight
- const w = parseInt(readLine());
- /* O(nw)
- let dp = Array.apply(null, Array(n + 1)).map(() => Array(w + 1).fill(0));
- for (let i = n - 1; i >= 0; i--) {
- for (let j = 0; j <= w; j++) {
- if (j < wv[i][0]) {
- dp[i][j] = dp[i + 1][j];
- } else {
- dp[i][j] = Math.max(dp[i + 1][j], dp[i + 1][j - wv[i][0]] + wv[i][1]);
- }
- }
- }
- console.log(dp[0][w]);
- */
- // minimum weight to value
- // O(n ∑i vi)
- const MAX_N = 100;
- const MAX_V = 100;
- let dp = Array.apply(null, Array(MAX_N + 1)).map(() =>
- Array(MAX_V + 1).fill(Infinity)
- );
- dp[0][0] = 0;
- for (let i = 0; i < n; i++) {
- for (let j = 0; j <= MAX_N * MAX_V; j++) {
- if (j < wv[i][1]) {
- dp[i + 1][j] = dp[i][j];
- } else {
- dp[i + 1][j] = Math.min(dp[i][j], dp[i][j - wv[i][1]] + wv[i][0]);
- }
- }
- }
- let res = 0;
- for (let i = 0; i <= MAX_N * MAX_V; i++) if (dp[n][i] <= w) res = i;
- console.log(res);
- }
Add Comment
Please, Sign In to add comment