在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。
输入
第1行,2个整数,N和W中间用空格隔开。N为物品的数量,W为背包的容量。(1 <= N <= 100,1 <= W <= 10000)
第2 - N + 1行,每行2个整数,Wi和Pi,分别是物品的体积和物品的价值。(1 <= Wi, Pi <= 10000)
输出
输出可以容纳的最大价值。
输入样例
3 6
2 5
3 8
4 9
输出样例
14
代码
import java.io.*;
public class nod1085 {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 1 << 16);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out), 1 << 16);
String[] s = reader.readLine().split("\\s+");
int N = Integer.parseInt(s[0]), W = Integer.parseInt(s[1]);
int[] weights = new int[N], prices = new int[N];
for(int i = 0; i < N; i++){
s = reader.readLine().split("\\s+");
weights[i] = Integer.parseInt(s[0]);
prices[i] = Integer.parseInt(s[1]);
}
// 纵向代表每个物品,横向代表剩余的空间,值代表总价值
int[][] f = new int[N + 1][W + 1];
for(int i = 1; i <= N; i++){
for(int j = 1; j <= W; j++){
// 如果剩余空间不足,则不加入
// 反之取不加入和加入中价值最大的一个
f[i][j] = weights[i - 1] > j ? f[i - 1][j] : Math.max(f[i - 1][j], f[i - 1][j - weights[i - 1]] + prices[i - 1]);
}
}
writer.write(f[N][W] + "");
writer.flush();
}
}