您的位置:首页 > 其它

hdu2660——Accepted Necklace

2017-07-17 22:49 141 查看
[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
For each case, output the highest possible value of the necklace.
 

[align=left]Sample Input[/align]

1
2 1
1 1
1 1
3

 

[align=left]Sample Output[/align]

1

 
题目大意:给你n个宝石,价值为a,重量为b,让你选择k个,重量不超过w的宝石,使得价值最大。

解题思路:搜索。在满足前提条件的情况下,尽可能的使总价值最大

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
struct Stone
{
int v,w;
}s[30];
int n,k,maxn,weight;
int vis[30];
void dfs(int cnt,int val,int wgt,int step)
{
if(cnt==k||weight==wgt)
{
if(val>maxn)
maxn=val;
return;
}
for(int i=step;i<n;i++)
{
if(!vis[i]&&cnt+1<=k&&wgt+s[i].w<=weight)
{
vis[i]=1;
dfs(cnt+1,val+s[i].v,wgt+s[i].w,i+1);
vis[i]=0;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d%d",&s[i].v,&s[i].w);
scanf("%d",&weight);
maxn=0;
dfs(0,0,0,0);
printf("%d\n",maxn);
}
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: