题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2660
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 4618 Accepted Submission(s): 1836 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.
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
题意:在n个石头中挑选k个,求总重量不超过w时石头的最大价值。
分析:深搜,对于数据较小来说,一般都不会超时的,搜每一种状态。
代码如下:
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
const int maxn = 40;
struct node
{
int value; //价值
int weight; //重量
}q[25];
int k,w,n,ans,vis[maxn];
void dfs(int x,int num,int va,int we)
{
if(num == k)
{
if(va > ans)
ans = va; //更新最大值
return; //已经找到最大值,回溯找下一轮
}
for(int i=x;i<n;i++)
{
if(we + q[i].weight <= w && num+1 <= k && !vis[i])
{
vis[i] = 1; //标记
dfs(i+1,num+1,va + q[i].value,we + q[i].weight); //向后面继续搜索
vis[i] = 0; //回溯
}
}
}
int main()
{
int t;
cin>>t;
while(t--)
{
memset(vis,0,sizeof vis);
ans = 0;
cin>>n>>k;
for(int i=0;i<n;i++)
{
cin>>q[i].value>>q[i].weight;
}
cin>>w;
dfs(0,0,0,0);
cout<<ans<<endl;
}
return 0;
}