题解 | 称砝码
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] weight = new int[n];
int[] count = new int[n];
for (int i = 0; i < n; i++) {
weight[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
count[i] = sc.nextInt();
}
System.out.print(getMax(weight,count));
}
public static int getMax(int[] weight,int[] count){
int len = weight.length;
int maxWeight = 0;
int result = 0;
for (int i = 0; i < len; i++) {
maxWeight = maxWeight + weight[i]*count[i];
}
int[] dp = new int[maxWeight + 1];
dp[0] = 1;
for (int i = 0; i < len; i++) {
for (int j = maxWeight; j >= 0; j--) {
if (dp[j] != 0){
for (int k = 0; k <= count[i]; k++) {
if (j + k*weight[i] <= maxWeight){
dp[j + k*weight[i]] = 1;
}
}
}
}
}
for (int i = 0; i <= maxWeight; i++) {
if (dp[i] == 1){
result++;
}
}
return result;
}
}
