0-1 Knapsack Problem
Description: There are $N$ items and one knapsack with a maximum capacity of $V$. Each item can be selected at most once (i.e., either take it or leave it). The $i\text{-th}$ item has a volume of $v_i$ and a value of $w_i$. Your task is to select a subset of items to put into the knapsack such that:
- The total volume of the selected items does not exceed the knapsack's capacity V.
- The total value of the selected items is maximized.
Output the maximum possible total value achievable under these constraints.
Input Format:
- Line 1: Two integers $N$ and $V$, separated by a space, representing the number of items and the capacity of the knapsack, respectively.
- Next $N$ lines: Each line contains two integers $v_i$ and $w_i$, separated by a space, representing the volume and value of the $i\text{-th}$ item.
Output Format: Output a single integer, the maximum total value of items that can be packed into the knapsack.
Constraints:
Sample Input:
Sample Output:
| |
As can be seen from the problem statement, our goal is to determine the optimal subset of items to pack into the knapsack to maximize the total value. Since each item can be selected at most once (the 0-1 knapsack constraint), the core idea is to iteratively determine the optimal selection when considering the $i\text{-th}$ item. This decision-making process can be formalized using the following dynamic programming recurrence relation:
$$ \text{dp}[i][j] = \max(\text{dp}[i-1][j], \text{dp}[i-1][j-v_i]+w_i)\tag{1-1} $$In the iteration where we decide whether to include the i-th item, we compare the total value obtained by including this item against the optimal value achieved without considering it (i.e., the optimal solution for the first $i\text{−1}$ items). This is a classic dynamic programming problem, and the corresponding implementation code is provided below:
| |
| |
| |
Complete Knapsack Problem
Description: There are $N$ items and a knapsack with capacity $V$. Each item can be selected any number of times. The $i\text{-th}$ item has volume $v_i$ and value $w_i$. Select items to maximize total value, with total volume $\le V$. Output the maximum value.
Input Format:
- Line 1: Two integers $N, V$ (number of items, knapsack capacity).
- Next $N$ lines: Each line has two integers $v_i$, $w_i$ (volume and value of the $i\text{-th}$ item).
Output Format: Output a single integer (maximum total value).
Constraints:
$$0\lt N,V \le 1000\\ 0\lt v_i, w_i \le 1000$$Sample Input:
Sample Output:
| |
| |