题解 | #称砝码# 官方解答动态规划java版本

称砝码

https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c

public class Main {
        private static int[] dp;
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            // 注意 hasNext 和 hasNextLine 的区别
            while (in.hasNextInt()) { // 注意 while 处理多个 case
                int n = in.nextInt();
                int[] weight = new int[n];
                int[] nums = new int[n];
                int sum =0;
                for (int i = 0; i < n; i++) {
                    weight[i] = in.nextInt();
                }
                for (int i = 0; i < n; i++) {
                    nums[i] = in.nextInt();
                    sum += nums[i] * weight[i];
                }
                dp = new int[sum+1];
                //array value is 0 by default
                dp[0] = 1;
                //initial condition
                for (int i = 0; i < weight.length; i++) {
                    for (int j = 0; j < nums[i]; j++) {
                        for (int k = sum; k >= weight[i]; k--) {
                            //we have to loop backwards so as not to double count one leverage
                            if (dp[k - weight[i]] == 1) {
                                dp[k] = 1;
                            }
                        }
                    }
                }
                System.out.println(Arrays.stream(dp).sum());
            }
        }
    }

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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