题解 | #称砝码#

称砝码

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

import java.util.*;

// java版
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) {
            Set<Integer> hashSet = new HashSet<>();
            hashSet.add(0);
            int cate = in.nextInt();
            int[] wei = new int[cate];
            int[] cnt = new int[cate];
            
            int total = 0;
            for (int i = 0; i < cate; i++) {
                wei[i] = in.nextInt();
            }
            for (int i = 0; i < cate; i++) {
                cnt[i] = in.nextInt();
                total += cnt[i];
            }
            int[] set = new int[total];
            int index = 0;
            for (int i = 0; i < cate; i++) {
                int curCnt = 0;
                while (curCnt < cnt[i]) {
                    set[index] = wei[i];
                    index++;
                    curCnt++;
                }
            }
            Set<Integer> ans = new HashSet<>(hashSet);
            for (int i = 0; i < total; i++) {
                
                for (int num : ans) {
                    hashSet.add(num + set[i]);
                }
                ans = new HashSet<>(hashSet);
            }

            System.out.println(ans.size());
            
        }
       
        
    }
}

全部评论

相关推荐

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

创作者周榜

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