题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
int kinds = Integer.parseInt(in.nextLine());
String weigs = in.nextLine();
String cous = in.nextLine();
String[] weiArr = new String[kinds];
String[] cousArr = new String[kinds];
weiArr = weigs.trim().split(" ");
cousArr = cous.trim().split(" ");
int [] weights = new int[kinds];
int [] counts = new int[kinds];
int times =0 ;
for(int i=0;i<kinds;i++){
// System.out.println("length:"+weiArr.length+"cou:"+cousArr.length);
weights[i] = Integer.parseInt(weiArr[i]);
counts[i] = Integer.parseInt(cousArr[i]);
}
times = findTheMostKinds(weights,counts);
System.out.println(times);
}
public static int findTheMostKinds(int[] weights,int[] counts){
int size = weights.length;
int toallweights = 0;
int nums =0;//统计可以测算出来的总数
//算出总量
for(int i=0;i<size;i++ ){
toallweights += weights[i] * counts[i];
}
boolean[] dp = new boolean[toallweights + 1];
dp[0] = true;
dp[toallweights] = true;
for(int i=0;i<size;i++){
for(int j= toallweights;j>=0;j--){
if(dp[j]){
for(int k=1;k<=counts[i] && j+k*weights[i] <= toallweights;k++){
dp[j+k*weights[i]] = true;
}
}
}
}
for(boolean bool:dp){
if(bool)
nums++;
}
// System.out.println("nums:"+nums);
return nums;
}
}
查看21道真题和解析