Accepted Necklace

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


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
 

Source
 

Recommend
zty



#include <iostream>  #include <limits>  using namespace std;  int c, n, k, max_w;  int max_val, sum_val, sum_w;   struct node  {      int val;      int w;      int visit;  }a[22];  void DFS(int start,int count)  //start循环开始点,count记录已用石头数  {      int i;      if(sum_w > max_w)   //剪枝          return ;         if(count > k)          return;      if(k == count && sum_w <= max_w)      {           if(max_val < sum_val)              max_val = sum_val;          return ;      }      for(i = start; i < n; i++)  //      if(a[i].visit == 0)      {          sum_val += a[i].val;          sum_w += a[i].w;          a[i].visit = 1;          DFS(i + 1, count + 1);                        sum_val -= a[i].val;          sum_w -= a[i].w;          a[i].visit = 0;      }  }  int main()  {      int i;      cin >> c;            while(c--)      {          cin >> n >> k;          for(i = 0; i < n; i++)          {                  cin >> a[i].val;              cin >> a[i].w;              a[i].visit = 0;          }          cin >> max_w;          sum_w = sum_val = max_val = 0;                    DFS(0, 0);          cout << max_val << endl;      }            return 0;  }