题目来源: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;
}