HDU-2660

题目
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.
Input
The first line of input is the number of cases.
For each case, the first line contains two integers N (N <= 20), the total number of stones, and K (K <= N), the exact number of stones to make a necklace.
Then N lines follow, each containing two integers: a (a<=1000), representing the value of each precious stone, and b (b<=1000), its weight.
The last line of each case contains an integer W, the maximum weight my mother will accept, W <= 1000.
Output
For each case, output the highest possible value of the necklace.
题目大意
有n个石头,每个石头有价值a[i],重量b[i],取K个石头且它们的重量不超过W,求最大价值。
解题思路
首先它的数据范围N<=20,数据比较小,每个石头有取与不取两种状态,可以用dfs将石头的状态所对应的价值求出来,取最大价值即可。时间复杂度为O(2^n)
代码实现

#include <cstdio>
using namespace std;
int num,v,ans,w,n,k,T;
int a[20],b[20];
void dfs(int x,int t)
{
	if (w>num || t>k) return;
	if (v>ans && t==k) ans=v;
	for (int i=x+1;i<=n;i++)
	  {
	  	 v+=a[i];
	  	 w+=b[i];
	  	 dfs(i,t+1);
	  	 v-=a[i];
	  	 w-=b[i];
	  }
}
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",&num);  
	  	  v=0;  
	  	  ans=-999999999;
	  	  dfs(0,0);  
	  	  printf("%d\n",ans);
	  }
} 
发布了13 篇原创文章 · 获赞 0 · 访问量 176

猜你喜欢

转载自blog.csdn.net/weixin_45723759/article/details/103953134