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
这题难度不大,有点01背包的意思,这里我们还是先用dfs做它。
我的AC代码:
#include<iostream>
#include<memory.h>
using namespace std;
const int maxn = 25;
int T, n, K, W;
int v[maxn];
int w[maxn];
int tag[maxn];
int max_res;
int value;
int weight;
void dfs(int k, int cnt) //cnt表示珍珠的个数
{
if(cnt == K)
{
if(max_res < value)
max_res = value;
return ;
}
//for(int i = 1;i <= n;i++) 跟全排列不同
for(int i = k;i <= n;i++)
{
if(tag[i] != 1 && weight + w[i] < W)
{
value += v[i];
weight += w[i];
tag[i] = 1;
dfs(i + 1, cnt + 1);
tag[i] = 0;
weight -= w[i];
value -= v[i];
}
}
}
int main()
{
cin >> T;
while(T-- > 0)
{
max_res = 0;
value = 0;
weight = 0;
memset(tag, 0, sizeof(tag));
cin >> n >> K;
for(int i = 1;i <= n;i++)
{
cin >> v[i] >> w[i];
}
cin >> W;
dfs(1, 0);
cout << max_res << endl;
}
return 0;
}
参数上做点修改就可以,当然cnt做全局变量也行。cnt用于记录现在项链的珍珠个数,一旦cnt的个数大于了要求的个数,那么就进入递归的边界条件
再就是for循环那一段稍微注意一下。
//for(int i = 1;i <= n;i++) 跟全排列不同
for(int i = k;i <= n;i++)
{
if(tag[i] != 1 && weight + w[i] < W)
{
value += v[i];
weight += w[i];
tag[i] = 1;
dfs(i + 1, cnt + 1);
tag[i] = 0;
weight -= w[i];
value -= v[i];
}
}
因为我的参数k表示现在处理到的珍珠序号,所以每次for循环当然是从第k个珍珠那里开始往后搜,前面的都是已经搜过的了,这里和全排列不一样,一开始我想当然地写成了从1开始,后来发现不对。
相关的,所以dfs(i + 1, cnt + 1)这里是i + 1而不是k + 1了
因为你一定是每次从第k个开始搜的,但进入if语句的时候,i可能就不是k的值了,而可能是大于k的某个值,所以这个时候if语句里面的dfs参数必须写i + 1才能表示是下一个要搜的珍珠序号!
时间:15MS