博客
关于我
【2019.1.22】【背包】纪中C组T3——小明逛超市
阅读量:357 次
发布时间:2019-03-04

本文共 1306 字,大约阅读时间需要 4 分钟。

小明有n元钱,想要购买m种物品来最大化他的需求度。每种物品有两种类型:一种只能买一件(z=1),另一种可以买无限件(z=0)。每件物品都有价格x和需求度y。目标是用n元钱购买物品,使得总需求度最大化。

方法思路

这个问题可以通过动态规划来解决,具体来说,涉及到0-1背包和完全背包的结合。对于每种物品,根据其类型分别处理:

  • 0-1背包处理:对于只能买一件的物品(z=1),用逆向填充的方法,确保每件物品只能被选一次。
  • 完全背包处理:对于可以买无限件的物品(z=0),用正向填充的方法,允许多次购买同一物品。
  • 具体步骤如下:

  • 初始化一个大小为n+1的数组dp,dp[j]表示用j元钱能达到的最大需求度,初始值为0。
  • 遍历每个物品,根据其类型更新dp数组。
  • 最终,dp[n]即为用n元钱能达到的最大需求度。
  • 解决代码

    #include 
    #include
    using namespace std;int main() { int n, m; cin >> n >> m; int ans[n+1]; fill(ans, ans + n + 1, 0); // 初始化dp数组为0 for (int i = 1; i <= m; ++i) { int x, y, z; cin >> x >> y >> z; if (z == 1) { // 0-1背包:逆向填充 for (int j = n; j >= x; --j) { if (j - x >= 0 && ans[j] < ans[j - x] + y) { ans[j] = max(ans[j], ans[j - x] + y); } } } else { // 完全背包:正向填充 for (int j = x; j <= n; ++j) { if (ans[j] < ans[j - x] + y) { ans[j] = max(ans[j], ans[j - x] + y); } } } } cout << ans[n] << endl; return 0;}

    代码解释

  • 初始化ans数组初始化为0,表示初始时没有钱可以花。
  • 遍历物品:每个物品根据类型处理。
    • z=1:逆向从n到x遍历,确保每件物品只能选一次。
    • z=0:正向从x到n遍历,允许多次购买同一物品。
  • 更新dp数组:在每次循环中,更新当前金额能达到的最大需求度。
  • 输出结果:打印用n元钱能达到的最大需求度,即ans[n]
  • 这个方法确保在有限的预算内,最大化需求度,适用于混合背包问题的典型场景。

    转载地址:http://euug.baihongyu.com/

    你可能感兴趣的文章
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>