题解 | #称砝码#

称砝码

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;
         

    }
}

全部评论

相关推荐

10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
渴望wlb的牛油果很...:直说卡第一学历不就行了 非得拐弯抹角
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务