[动态规划] NYOJ311 完全背包问题

题目

这里写图片描述

思路

1.状态及指标函数:d(S),S->0的最大边权路
2.状态转移方程:

d(i)=/left/d[iVx]+Wx/right/ d ( i ) = / l e f t / d [ i − V x ] + W x / r i g h t /

3.本题NYOJ有点卡常的感觉,记忆化搜索TLE,普通递推TLE,必须把递推的顺序反以下才能AC。

代码

1.记忆化搜索

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#define _for(i,a,b) for(int i = (a); i<(b); i++)
#define _rep(i,a,b) for(int i = (a); i<=(b); i++)
using namespace std;

const int INF = 1 << 30;
const int maxn = 2000 + 10;
const int maxx = 50000 + 100;
int n, C, V[maxn], d[maxx], W[maxn];

int dp(int S) {
    int &ans = d[S];
    if (ans != -1) return ans;
    ans = -INF;
    _for(i, 0, n)
        if (S >= V[i])
            ans = max(ans, dp(S - V[i]) + W[i]);
    return ans;
}

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &C);
        _for(i, 0, n) scanf("%d%d", &V[i], &W[i]);

        memset(d, -1, sizeof(d));
        d[0] = 0;
        int ans = dp(C);

        if (ans <= 0) printf("NO\n");
        else printf("%d\n", ans);
    }

    return 0;
}

2.递推

// 唯一能AC的代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#define _for(i,a,b) for(int i = (a); i<(b); i++)
#define _rep(i,a,b) for(int i = (a); i<=(b); i++)
using namespace std;

const int INF = 1 << 30;
const int maxn = 2000 + 10;
const int maxx = 50000 + 100;
int n, C, V[maxn], d[maxx], W[maxn];

int main() {
    int T;
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &C);
        _for(i, 0, n) scanf("%d%d", &V[i], &W[i]);

        _rep(i, 0, C) d[i] = -INF;
        d[0] = 0;

        // 注意此处把枚举的顺序反了,一般不这么做,本题是为了AC
        _for(i, 0, n)
            _rep(S, V[i], C)
                    d[S] = max(d[S], d[S - V[i]] + W[i]);

        if (d[C] <= 0) printf("NO\n");
        else printf("%d\n", d[C]);
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值