网易真题-牛牛的背包问题

题目来源:https://www.nowcoder.com/question

题意

中文题意不再解释。

思路

首先看数据范围,如果背包的容量小的话就使用DP,这里显然很大,但是n的数量挺小,然后就想到了dfs暴力。。0,1,参考大神的代码,优化的就是将零食按照重量进行排序,适当剪枝。

代码

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long LL;

int n;
LL w,res;
LL V[60];

void dfs(LL sum,int index)
{
    if(sum>w)
        return ;
    if(sum<=w)
        res++;
    for(int i=index; i<n; i++)
    {
        dfs(sum+V[i],i+1);
    }
}

int main()
{
    LL sumW=0;
    scanf("%d%lld",&n,&w);
    for(int i=0; i<n; i++)
    {
        scanf("%lld",&V[i]);
        sumW+=V[i];
    }
    if(sumW<=w)
    {
        res=pow(2,n);
    }
    else
    {
        sort(V,V+n);
        dfs(0,0);
    }
    printf("%lld\n",res);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值