资源限制
内存限制:256.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
这里很感谢广大同行们的思路:
这道题目是一个动态规划题。我们用 F [ i ][ j ] = true / false 表示用前i个砝码能/不能称量重量为 j的物体,假如我们用前 i-1 个砝码能够称出重量为 w 的物体,那么我们加上第 i 个砝码就能够称重重量为 w+w[i] 的物体以及重量为 w-w[i] 或者 w[i]-w 的物体,大体思路就是这样。
代码:
import java.util.Scanner;
public class Main1 {
public static void balanWeighing(int n, int[] weight, int sum){
boolean[][] mat = new boolean[n+1][sum+1];
mat[0][0] = true;
for(int i = 1; i <= n; i++) {
for(int j = 0; j <= sum; j++) {
//如果第 i - 1 个砝码能称出 j 的重量,则进入if
if(mat[i-1][j] == true) {
mat[i][j] = true; //直接设置成true(代表 j 可以被称出)
mat[i][j+weight[i-1]] = true; //同时 j + w[i-1] 的重量也可以被称出
//大的重量减小的,就不会越界
if(j > weight[i-1]) {
mat[i][j-weight[i-1]] = true;
}else {
mat[i][weight[i-1]-j] = true;
}
}
}
}
//统计最后一行的 true 的个数 (第0列不算在内)
int ans = 0;
for(int i = 1; i <= sum; i++) {
if(mat[n][i]) {
ans++;
}
}
System.out.println(ans);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] ret = new int[n];
int sum = 0;
for(int i = 0; i < n; i++) {
ret[i] = sc.nextInt();
sum += ret[i];
}
balanWeighing(n,ret,sum);
}
}