hdu2660——Accepted Necklace

来源:互联网 发布:庞青云知乎 编辑:程序博客网 时间:2024/06/05 06:51
Problem Description
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.
 

Sample Input
1 2 1 1 1 1 1 3
 

Sample Output
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;}



原创粉丝点击