Accepted Necklace/HDU 2660/DFS

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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值