hihoCoder 1043 : 完全背包

本文详细解析了一种背包问题的动态规划解法,通过使用二维数组进行状态压缩优化空间复杂度,实现了高效的求解过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:见原题。


思路:dp(i,j)表示用体积j来装前i个物体能得到的最大价值,由于第i个物品可以装多次,所以转移方程应该是dp(i,j)=max{dp(i,jneed(i)),dp(i1,j)}
空间优化:dp(i,2)用来滚动得到当前的值,注意递增枚举体积,因为大的体积依赖于小的体积。

AC代码

#include <cstdio>
#include <cmath>
#include <cctype>
#include <bitset>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000") 
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int> 
typedef long long LL;
const int maxn = 1e5 + 5;
int dp[maxn][2];
int need[505], value[505];
int main() {
    int n, V;
    while(scanf("%d%d", &n, &V) == 2) {
        for(int i = 1; i <= n; ++i) {
            scanf("%d%d", &need[i], &value[i]);
        }
        memset(dp, 0, sizeof(dp));
        int f = 1;
        for(int i = 1; i <= n; ++i) {
            for(int j = 0; j <= V; ++j) {
                if(j < need[i]) dp[j][f] = dp[j][f^1]; 
                else dp[j][f] = max(dp[j][f^1], dp[j-need[i]][f]+value[i]);
            }
            f ^= 1;
        }
        printf("%d\n", dp[V][f^1]);
    }
    return 0;
}

如有不当之处欢迎指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值