------------------------
package com.supermars.practice;
import java.util.Scanner;
public class 背包01问题规划方向f {
static Scanner cin = new Scanner(System.in);
public static void main(String[] args) {
// i层剩余容量j
// d[i,j]=max{d(i+1,j),d(i+1,j-V[i])+W[i])}
while (cin.hasNext()) {
int n = cin.nextInt();
int C = cin.nextInt();
int V[] = new int[n + 1];
int W[] = new int[n + 1];
int f[][] = new int[C + 1][C + 1];// 目标状态d
for (int i = 0; i < n; i++) {
V[i] = cin.nextInt();
W[i] = cin.nextInt();
}
//f(i,j)=max{f(i-1,j),f(i-1,j-V[i])+W[i]}
for (int i =1; i <=n; i++) {//层
for (int j = 0; j <=C; j++) {//当前量
f[i][j]=(i==1?0:f[i-1][j]); //不选
if(j>=V[i]){ //选择
f[i][j]=Math.max(f[i][j],f[i-1][j-V[i]]+W[i]);
}
}
}
System.out.println(f[n][C]);
}
}
}
------------------------
package com.supermars.practice;
import java.util.Scanner;
public class 背包01滚动数组 {
static Scanner cin = new Scanner(System.in);
public static void main(String[] args) {
// i层剩余容量j
// d[i,j]=max{d(i+1,j),d(i+1,j-V[i])+W[i])}
while (cin.hasNext()) {
int n = cin.nextInt();
int C = cin.nextInt();
int V[] = new int[n + 1];
int W[] = new int[n + 1];
int f[] = new int[C + 1];// 目标状态d
for (int i = 0; i < n; i++) {
V[i] = cin.nextInt();
W[i] = cin.nextInt();
}
// f(i,j)=max{f(i-1,j),f(i-1,j-V[i])+W[i]}
for (int i = 1; i <= n; i++) {// 层
for (int j = C; j >= 0; j--) {// 当前量
if (j >= V[i])
f[j] = Math.max(f[j], f[j - V[i]] + W[i]);
}
}
System.out.println(f[C]);
}
}
}