HDU 2660 Accepted Necklace (01背包,dfs)

来源:互联网 发布:淘宝童装货源 编辑:程序博客网 时间:2024/05/17 07:27

Accepted Necklace

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3696 Accepted Submission(s): 1465

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个宝石,串一个项链,要求只能用k个宝石,且重量不能超过w,给出每个宝石的重量和价值,要求价值最大。

分析

  该题目是简单的01背包,只是约束条件加了选择物品的个数。数据量比较小,直接搜索就可以过。

代码如下

#include <stdio.h>int n,k,m;int value[25],weight[25];int maxVal;void dfs(int t,int num,int val,int wei){    if(num>k || wei>m)        return ;    if(t==n)    {        if(val>maxVal)            maxVal=val;        return ;    }    dfs(t+1,num+1,val+value[t],wei + weight[t]);    dfs(t+1,num,val,wei);}int main(){    int T;    int i,j;    scanf("%d",&T);    while(T--)    {        scanf("%d %d",&n,&k);        for(i=0;i<n;i++)            scanf("%d %d",value+i,weight+i);        scanf("%d",&m);        maxVal=-1;        dfs(0,0,0,0);        printf("%d\n",maxVal);    }    return 0;}
0 0