杭电2602--Bone Collector(01背包)

01背包问题详解
本文详细解析了01背包问题的两种实现方法:一种使用二维动态规划数组,另一种使用一维动态规划数组并提供源代码示例。通过这两种方法,读者可以更好地理解和掌握01背包问题的解决思路。
 
Input
The first line contain a integer T , the number of cases.
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.
 

Output
One integer per line representing the maximum of the total value (this number will be less than 2 31).
 

Sample Input
1 5 10 1 2 3 4 5 5 4 3 2 1
 

Sample Output
14
 

Author
Teddy
 

Source
 

Recommend
lcy   |   We have carefully selected several similar problems for you:   1203  2159  2955  1171  2191 
 
RE: 01背包基础题:
 
//感觉这个比较好理解:   46ms  
#include <cstdio>
#include <cstring>
#include <iostream>
#define max(a, b) a>b?a:b
using namespace std;
int dp[1010][1010], val[1010], vol[1010];
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        int n, v;
        scanf("%d %d", &n, &v);
        for(int i = 1; i <= n; i++)
            scanf("%d", &val[i]);
        for(int i = 1; i <= n; i++)
            scanf("%d", &vol[i]);
        for(int i = 1; i <= n; i++)
        {
            for(int j = 0; j <= v; j++)  //容量; 
            {
                if(j < vol[i])
                    dp[i][j] = dp[i-1][j];
                else
                    dp[i][j] = max(dp[i-1][j], dp[i-1][j-vol[i]] + val[i]);    
            } 
        }
        printf("%d\n", dp[n][v]);
    }
    return 0;    
} 

 

//比二维数组稍微快点; 31ms 
#include <cstdio>
#include <cstring>
#include <iostream>
#define max(a, b) a>b?a:b 
using namespace std;
int dp[1010], val[1010], vol[1010];
int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        int n, v;
        scanf("%d %d", &n, &v);
        for(int i = 1; i <= n; i++)
            scanf("%d", &val[i]);
        for(int j = 1; j <= n; j++)
            scanf("%d", &vol[j]);
        memset(dp, 0, sizeof(dp)); 
        for(int k = 1; k <= n; k++)
        {
            for(int Q = v; Q >= vol[k]; Q--)
            {
                dp[Q] = max(dp[Q], dp[Q - vol[k]] + val[k]); 
            } 
            
        }
        printf("%d\n", dp[v]);
    }
    return 0;    
} 

 

转载于:https://www.cnblogs.com/soTired/p/4763252.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值