题目描述
完全背包
无优化
import java.util.*;
public class Main{
static int N = 1010;
static int n, m;
static int[] v = new int[N];
static int[] w = new int[N];
static int[][] f = new int[N][N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for (int i = 1; i <= n; i ++ ){
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int i = 1; i <= n; i ++ ){
for (int j = 1; j <= m; j ++ ){
//k表示的是当前物品用几次 k*v[i] <= j去判断能否装的下
for(int k = 0; k*v[i] <= j ; k++)
f[i][j] = Math.max(f[i][j], f[i-1][j-k*v[i]] + k*w[i]);
}
}
System.out.println(f[n][m]);
}
}
有优化
import java.util.*;
public class Main{
static int N = 1010;
static int n, m;
static int[] v = new int[N];
static int[] w = new int[N];
static int[] f = new int[N];
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
for (int i = 1; i <= n; i ++ ){
v[i] = sc.nextInt();
w[i] = sc.nextInt();
}
for (int i = 1; i <= n; i ++ ){
for (int j = v[i]; j <= m; j ++ ){
f[j] = Math.max(f[j], f[j - v[i]] + w[i]);
}
}
System.out.println(f[m]);
}
}