AcWing 9. 分组背包问题
原题链接
中等
作者:
涛声依旧
,
2021-04-10 01:29:09
,
所有人可见
,
阅读 1
不懂可加微信15809238643交流
import java.util.Scanner;
public class Main{
public static void main(String[] args){
int KMax = 102;
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int V = sc.nextInt();
int[][] v = new int[N+1][KMax];//体积
int[][] w = new int[N+1][KMax];//价值
for (int i = 1; i < N+1; i++) {
int K = sc.nextInt();
for (int k = 1; k <= K; k++) {
v[i][k] = Integer.parseInt(sc.next());//第 i 组的体积
w[i][k] = Integer.parseInt(sc.next());//第 i 组的价值
}
}
int[][] s = new int[N+1][V+1];
for (int i = 1; i < N+1; i++) {
for (int j = 1; j < V+1; j++) {
s[i][j] = s[i-1][j];//不选物品
for (int k = 1; v[i][k] !=0 ; k++) {//循环选择k个物品
if (j >= v[i][k]) {
s[i][j] = Math.max(s[i][j],s[i-1][j-v[i][k]] + w[i][k]);
}
}
}
}
System.out.println(s[N][V]);
}
}