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

    你可能感兴趣的文章
    Nodejs教程09:实现一个带接口请求的简单服务器
    查看>>
    Nodejs简介以及Windows上安装Nodejs
    查看>>
    nodejs系列之express
    查看>>
    nodejs配置express服务器,运行自动打开浏览器
    查看>>
    Node入门之创建第一个HelloNode
    查看>>
    Node出错导致运行崩溃的解决方案
    查看>>
    node安装及配置之windows版
    查看>>
    Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
    查看>>
    NOIp2005 过河
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>