Accepted Necklace
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2218 Accepted Submission(s): 863
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<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)
{
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;
}