9. 分组背包问题
作者:
dsf2
,
2021-03-04 07:19:08
,
所有人可见
,
阅读 360
import java.util.*;
class Main {
public static int knapsackWithGroup(List<Integer>[] values, List<Integer>[] weights, int capacity) {
int n = values.length; // values index start from 1
int[][] dp = new int[n][capacity + 1];
for (int i = 1; i < n; i++)
for (int c = 0; c <= capacity; c++) {
dp[i][c] = dp[i - 1][c];
for (int j = 0; j < values[i].size(); j++) {
if (weights[i].get(j) <=c)
dp[i][c] = Math.max(dp[i][c], dp[i - 1][c - weights[i].get(j)] + values[i].get(j));
}
}
return dp[n - 1][capacity];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), c = sc.nextInt();
List<Integer>[] values = new ArrayList[n + 1];
List<Integer>[] weights = new ArrayList[n + 1];
int cnt = 0;
String l = null;
sc.nextLine();
while (sc.hasNext()) {
String input = sc.nextLine();
String[] vals = input.split(" ");
if (vals.length == 1) {
cnt++;
values[cnt] = new ArrayList<Integer>();
weights[cnt] = new ArrayList<Integer>();
} else {
values[cnt].add(Integer.parseInt(vals[1]));
weights[cnt].add(Integer.parseInt(vals[0]));
}
}
System.out.println(knapsackWithGroup(values, weights, c));
}
}