思想
思想:类似于多重背包问题,多重背包是可以选第i个物品至多s[i]件,此题只允许选一件,每件体积和重量不同。
最终还是转化为01背包问题,选不选第x个的问题
java 代码
import java.io.*;
import java.lang.*;
class Main{
static int n = 0, m = 0, N = 110;
static int[][] f = new int[N][N];
static int[][] v= new int[N][N], w = new int[N][N];
static int[] s = new int[N];
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String[] params = buf.readLine().split(" ");
n = Integer.valueOf(params[0]);
m = Integer.valueOf(params[1]);
for(int i = 1; i <= n; ++i){
int cnt = Integer.valueOf(buf.readLine());
s[i] = cnt;//记录每组的数量
for(int j = 1; j <= cnt; ++j){
String[] info = buf.readLine().split(" ");
int a = Integer.valueOf(info[0]);
int b = Integer.valueOf(info[1]);
v[i][j] = a;
w[i][j] = b;
}
}
for(int i = 1; i <= n; ++i){
for(int j = 0; j <= m; ++j){
f[i][j] = f[i - 1][j];
for(int x = 0; x <= s[i]; ++x){
if(v[i][x] <= j)
f[i][j] = Math.max(f[i][j], f[i - 1][j - v[i][x]] + w[i][x]);
}
}
}
System.out.print(f[n][m]);
}
}