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
Sample Output
Input
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.
1 2 1 1 1 1 1 3
1
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
struct node{int value,weight;};
node a[30];int K,n,W;int flag[30];
int wei=0,va=0,maxa=0;
void dfs(int cur,int _wei,int _value,int pre)//关键在于pre指针,它将上一层选择的宝石位置传递下来,并从下一个开始判断是否满足条件,这样避免了从头
{
if(cur==K){maxa=_value>maxa?_value:maxa;return;}//头开始再去判断,节省了很多时间(之所以直接从下一个直接判断,是因为之前的宝石在上一层已判)
for(int i=pre;i<n;i++)
{
if(!flag[i]&&_wei+a[i].weight<=W)
{
flag[i]=1;
dfs(cur+1,_wei+a[i].weight,_value+a[i].value,i+1);
flag[i]=0;
}
}
}
int main()
{
int t;cin>>t;
while(t--)
{
cin>>n>>K;
for(int i=0;i<n;i++)cin>>a[i].value>>a[i].weight;
cin>>W;memset(flag,0,sizeof(flag));
dfs(0,0,0,0);
printf("%d\n",maxa);
}
}