Accepted Necklace/HDU 2660/DFS
题目
I have N precious stones, and plan to use K of them to make a necklace for my mother, but she won’t accept a necklace which is too heavy. Given the value and the weight of each precious stone, please help me find out the most valuable necklace my mother will accept.
题目来源:HDU 2660
题目链接
题意
有n颗宝石,每颗宝石有其重量和价值,我们需要从中选k颗,使得重量总和小于W,且价值总和最大。
解法
因为宝石数量较少,最多20颗,我们可以用DFS来暴力做,即枚举每颗宝石选还是不选。
代码:
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int T,n,k,w,ans,sum,sa,sb,f[30],a[30],b[30];
void dfs(int x)
{
if (x>n)
{
sum=sa=sb=0;
for (int i=1;i<=n;i++) if (f[i]) sum++,sa+=a[i],sb+=b[i];
if (sum!=k) return;
if (sb>w) return;
if (sa>ans) ans=sa;
return;
}
f[x]=0;
dfs(x+1);
f[x]=1;
dfs(x+1);
}
int main()
{
scanf("%d",&T);
while (T--)
{
scanf("%d%d",&n,&k);
for (int i=1;i<=n;i++) scanf("%d%d",&a[i],&b[i]);
scanf("%d",&w);
ans=0;
dfs(1);
printf("%d\n",ans);
}
return 0;
}