可以把0置成true,其他所有都是false。
然后排序,跑一遍完全背包。
Java 代码
import java.util.Scanner;
import java.util.Arrays;
class Main {
private static void solve(int[] arr, int n, boolean[] dp, StringBuilder sb) {
Arrays.sort(arr, 0, n);
for (int i = 1; i <= arr[n - 1]; ++i) {
dp[i] = false;
}
int cnt = n;
for (int i = 0; i < n; ++i) {
if (dp[arr[i]]) {
cnt--;
continue;
}
for (int j = arr[i]; j <= arr[n - 1]; ++j) {
dp[j] |= dp[j - arr[i]];
}
}
sb.append(cnt).append("\n");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
boolean[] dp = new boolean[25001];
dp[0] = true;
int[] arr = new int[101];
StringBuilder sb = new StringBuilder();
for (int j = 0; j < T; ++j) {
int n = in.nextInt();
for (int i = 0; i < n; ++i) {
arr[i] = in.nextInt();
}
solve(arr, n, dp, sb);
}
in.close();
System.out.print(sb);
}
}