hdu 2660 Accepted Necklace(简单DFS)

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
 
刚开始就隐隐约约是贪心了,读完题目觉得可能是个复杂的dp,可是数据N小于等于20,呵呵,用暴力之王DFS就搞定了!
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 #define N 25
 6 int v[N],w[N];
 7 int n,m;
 8 int lim;
 9 int sum;
10 void DFS(int a,int b,int c,int d)//a 当前价值 b当前重量 c已经采用的宝石 遍历到的宝石下标
11 {
12      if(b>lim)//如果重量超过了限制
13          return ;
14      if(c>m)//如果采用的宝石超过了限制返回
15          return ;
16      int rest=0;
17      for(int i=d;i<n;i++)
18          rest+=v[i];
19      if(a+rest<sum)//优化一下  15ms变0ms
20          return ;
21      if(sum<a)
22      {
23          sum=a;
24      }
25      int j;
26      for(j=d;j<n;j++)
27      {
28          DFS(a+v[j],b+w[j],c+1,j+1);
29      }
30 }
31 int main()
32 {
33     int t;
34     scanf("%d",&t);
35     while(t--)
36     {
37         memset(v,0,sizeof(v));
38         memset(w,0,sizeof(w));
39         scanf("%d%d",&n,&m);
40         int i;
41         for(i=0;i<n;i++)
42             scanf("%d%d",&v[i],&w[i]);
43         scanf("%d",&lim);
44         sum=0;
45         DFS(0,0,0,0);
46         printf("%d\n",sum);
47     }
48     return 0;
49 }

 

 

你可能感兴趣的:(HDU)