hdu 2660 Accepted Necklace 【dfs】

题目链接: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.
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 

题意:在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;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值