AcWing 3. Java完全背包问题
原题链接
简单
作者:
亦与余hhh
,
2021-03-16 15:51:19
,
所有人可见
,
阅读 248
Java 代码
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
int[] w = new int[N + 1];
int[] val = new int[N + 1];
int[] dp = new int[M + 1];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 1; i <= N; i++) {
w[i] = sc.nextInt();
val[i] = sc.nextInt();
}
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++) {
if (i - w[j] >= 0) {
dp[i] = Math.max(dp[i], dp[i - w[j]] + val[j]);
}
}
}
System.out.println(dp[M]);
}
}