秋招算法——背包模型——423采药问题——模板:背包问题

文章目录

题目描述
思路分析
  • 这里明显是使用背包问题,所以这里参考一下背包这个模板题的内容
  • 这个是朴素版的模板,没有经过代码的优化
cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1100;
const int V = 1100;
int n,v;  // 分别表示背包物体的数量和背包的容量
int f[N][V];  // 这个是状态转移矩阵
int vs[N];  // 不同物体的容量矩阵
int ws1[N];  // 不同物体的价值矩阵

int main(){
    cin>>n>>v;
    for(int i = 1 ;i <= n;i ++){
        cin>>vs[i]>>ws1[i];
    }
    // 这里需要迭代两次进行计算
    for (int i = 1; i <= n; ++i) {
        for (int j = 0; j <= v ; ++j) {
            f[i][j] = max(f[i -1][j],f[i][j]);
            if (j >= vs[i])
                f[i][j] = max(f[i][j],f[i - 1][j - vs[i]] + ws1[i]);    
        }
        
    }
}
  • 下述是经过优化之后的模板
    • 主要是使用了滚动数组,并且优化了空间之后的操作
cpp 复制代码
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1100;
const int V = 1100;
int n,v;
int f[N];
int vs[N];
int ws1[N];

int main(){
    cin>>n>>v;
    for(int i = 1 ;i <= n;i ++){
        cin>>vs[i]>>ws1[i];
    }

    for (int i = 1; i <= n; ++i) {
        for (int j = v; j >= 0 && j >= vs[i]; --j) {
                f[j] = max(f[j],f[j - vs[i]] + ws1[i]);
        }

    }

    cout<<f[v];
}

背包问题总共有三种,分别是求最大值、最小值和方案数量

实现代码
cpp 复制代码
// 组合数问题
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 110;
const int M = 11000;
int f[M],g[N];

int main(){
    int n, m;
    cin>>n>>m;
    for(int i = 1;i <= n;i ++) cin>>g[i];
    f[0] = 1;
    for (int i = 1; i <= n; ++i) {
        for (int j = m; j >= 1 && j >= g[i]; --j) {
//            f[j] = max(f[j],f[j - g[i]] + g[i]);
            f[j] = f[j] + f[j - g[i]];
        }
    }
    cout<<f[m]<<endl;

}
分析总结
  • 这里要明白最大值、最小值和装载货物数量之间的关系。
  • 同时还要记住这是一个模板题,记住模板就是会做。
相关推荐
wen__xvn1 小时前
每日一题洛谷P1914 小书童——凯撒密码c++
数据结构·c++·算法
BUG 劝退师2 小时前
八大经典排序算法
数据结构·算法·排序算法
m0_748240912 小时前
SpringMVC 请求参数接收
前端·javascript·算法
小林熬夜学编程2 小时前
【MySQL】第八弹---全面解析数据库表的增删改查操作:从创建到检索、排序与分页
linux·开发语言·数据库·mysql·算法
小小小白的编程日记2 小时前
List的基本功能(1)
数据结构·c++·算法·stl·list
_Itachi__2 小时前
LeetCode 热题 100 283. 移动零
数据结构·算法·leetcode
柃歌2 小时前
【UCB CS 61B SP24】Lecture 5 - Lists 3: DLLists and Arrays学习笔记
java·数据结构·笔记·学习·算法
鱼不如渔3 小时前
leetcode刷题第十三天——二叉树Ⅲ
linux·算法·leetcode
qwy7152292581633 小时前
10-R数组
python·算法·r语言
月上柳梢头&3 小时前
[C++ ]使用std::string作为函数参数时的注意事项
开发语言·c++·算法