题解 | #称砝码#

称砝码

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

#include <stdio.h>
#include <string.h>
//不会做,借助榜一大佬的方法
int main() {
    int n;
  //输入所有的数据
    while (scanf("%d", &n) != EOF) {
        int weight[n],num[n],i,j,k,total=0;
        for(i=0;i<n;i++) scanf("%d",&weight[i]);
        for(i=0;i<n;i++) scanf("%d",&num[i]);
  //计算出最大的重量
        for(i=0;i<n;i++)
        total+=weight[i]*num[i];
  //创建哈希表,表的下标代表重量,表的0或1代表这个重量是否能取到
        int hash[total+1];
        memset(hash,0,sizeof(hash));
        hash[0]=1;
  //循环,如果某个重量存在,则这个重量加上砝码的重量也存在
        for(i=0;i<n;i++)
        for(j=0;j<num[i];j++)
        for(k=total;k>=0;k--)//反向确认循环,正向的话会污染哈希表
            if(hash[k]==1) hash[k+weight[i]]=1;
   //计算所有存在的重量     
        int count=0;
        for(i=0;i<total+1;i++)
        if(hash[i]==1) count++;

        printf("%d",count);

    }
    return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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