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 

Subject description:

N k selected in a gem, making him the total value of the largest, with a total weight of not more than W.

analysis:

Since the number n is small, so do with dfs. n constitute a collection of gems, we use dfs to traverse all of his subset. For as long as each gem, and we choose not vote, they constitute a set of 2 ^ n, is his subset.

To update the maximum value max set whenever dfs end condition, and options enough k member.

To set two parameters, such as i + 1 is selected from the group, i is not selected. j + 1 to have access to the stones.

Plus the value of each item, weight, time to pay attention to is the j-th instead of the i-th.

Code:

#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;
}

Guess you like

Origin www.cnblogs.com/studyshare777/p/12190105.html