题解 | #称砝码#动态规划
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
int[] weights = new int[n];
int[] quantities = new int[n];
for (int i = 0; i < n; i++) {
weights[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
quantities[i] = scanner.nextInt();
}
int result = countDistinctWeights(weights, quantities);
System.out.println(result);
}
}
public static int countDistinctWeights(int[] weights, int[] quantities) {
int maxWeight = 0;
for (int i = 0; i < weights.length; i++) {
maxWeight += weights[i] * quantities[i];
}
boolean[] dp = new boolean[maxWeight + 1];
dp[0] = true;
for (int i = 0; i < weights.length; i++) {
for (int j = maxWeight; j >= weights[i]; j--) {
for (int k = 1; k <= quantities[i] && k * weights[i] <= j; k++) {
dp[j] |= dp[j - k * weights[i]];
}
}
}
int count = 0;
for (boolean value : dp) {
if (value) {
count++;
}
}
return count;
}
}
