D - DFS HDU - 2660

D - DFS

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.

Sample Input

1 
2 1 
1 1 
1 1 
3 

Sample Output

1 

题目描述:

在n个宝石中选k个,使他总价值最大,总重不大于W。

分析:

因为n的数很小,所以用dfs来做。n个宝石构成一个集合,我们要用dfs遍历他的所有子集。只要对于每个宝石,我们选和不选,就构成2^n个集合,就是他的子集。

只要dfs设置好结束条件,和选够k件时更新下最大值max即可。

要设置2个参数,如i+1为选,i为不选。j+1为已经访问该宝石。

加上每个物品价值,重量,时要注意是第j个,而不是第i个。

代码:

#include<iostream> 
#include<algorithm>
#define MAX(x,y) x>y?x:y;
using namespace std;
int k,W,n;
int m=0;
int w[30];
int v[30];
int dfs(int i,int sum,int value,int j)
{   
    if(sum>W) return 0;
    if(j>n) return 0;
    if(i==k) return m=MAX(m,value);
    
    dfs(i+1,sum+w[j],value+v[j],j+1);
    dfs(i,sum,value,j+1);
    
    return 0;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        scanf("%d %d",&n,&k);
        for(int i=0;i<n;i++)
        {
            cin>>v[i];
            cin>>w[i];
        }
        cin>>W;
        m=0; 
        dfs(0,0,0,0);
        printf("%d\n",m);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/studyshare777/p/12190105.html