博客
关于我
【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/

    你可能感兴趣的文章
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>