2019 GDUT 新生专题I选集 D题 Accepted Necklace(HDU-2660)

D - DFS

链接
来源:Accepted Necklace(HDU-2660)

题目描述
给一些宝石,每个宝石都有自己的重量和价值,要求选取一定数量的宝石组成一条项链,使项链的重量不超过佩戴者能接受的最大重量,且价值最高。

题目分析
本来比较像一道dp题,但数据比较少,直接dfs即可。

代码

#include <cstdio>
using namespace std;

int value[1000];
int weight[1000];
int n,need,maxw,ans=-1;

void dfs(int va,int we,int record,int choose)
{
	if(we>maxw) return;
	if(choose>need) return;
	if(record==n){
		ans=va>ans?va:ans;
		return;
	}
	dfs(va+value[record],we+weight[record],record+1,choose+1);
	dfs(va,we,record+1,choose);
}

int main()
{
	int ca;
	scanf("%d",&ca);
	while(ca--){
		scanf("%d%d",&n,&need);
		for(int i=0;i<n;i++)
			scanf("%d%d",value+i,weight+i);
		scanf("%d",&maxw);
		dfs(0,0,0,0);
		printf("%d\n",ans);
	}
}

发布了24 篇原创文章 · 获赞 1 · 访问量 682

猜你喜欢

转载自blog.csdn.net/palax0/article/details/103969156