当前位置:网站首页>最基础01/完全背包
最基础01/完全背包
2022-07-30 11:58:00 【Codiplay】
给定
个正整数
从中取出若干个数,使它们的和为 M,求有多少种选择方案。
因为每个数只能用一次,所以是0|1背包。
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 110;
int f[N][11100];
int a[N];
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
f[0][0] = 1;
for (int i = 1; i <= n; i ++ ) {
for (int j = 0; j <= m; j ++ ) {//j必须从0开始,初始化简单,而且符合定义
f[i][j] = f[i - 1][j]; //不选
if(a[i] <= j) f[i][j] += f[i - 1][j - a[i]];//能选的前提下选
}
}
cout << f[n][m] << '\n';
return 0;
}因为阶段i都是由阶段i-1更新而来,0/1的经典优化——倒叙循环。保证用i-1更新i阶段
将“阶段”隐藏起来了,f[i]表示总和为i
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 11000;
int f[N];
int a[N];
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i ++ ) cin >> a[i];
f[0] = 1;
for (int i = 1; i <= n; i ++ ) {
for (int j = m; j >= a[i]; j -- ) {
f[j] += f[j - a[i]];
}
}
cout << f[m] << '\n';
return 0;
}
从1到n可以取无数次,112和211是一种方案,完全背包
完全背包正序。
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N = 11000;
const int mod = 1e9 + 7;
int f[N];
int main(){
//std::ios::sync_with_stdio(false);
//std::cin.tie(nullptr);
int n;
cin >> n;
f[0] = 1;
for (int i = 1; i <= n; i ++ ) {
for (int j = i; j <= n; j ++ ) {
f[j] = (f[j] + f[j - i]) % mod;
}
}
cout << f[n] << '\n';
return 0;
}边栏推荐
- Vivado安装后添加器件库
- 柔性机械系统分布参数建模及其控制的研究与进展
- 来n遍剑指--04. 二维数组中的查找
- Transfer Learning Technology Training
- Matlab基础(0)——命令行常用指令
- 和数集团:让智慧城市更智慧,让现实生活更美好
- PanGu-Coder: Function-level code generation model
- 崩了,该来的终究躲不掉
- Manage reading notes upward
- Based on the analysis of the acoustic channel cable tunnel positioning technology
猜你喜欢

win下怎么搭建php环境的方法教程

Unity Beginner 6 - Simple UI production (blood bar production) and audio addition and NPC dialogue bubbles (2d)

Rust from entry to proficient 02-installation

亚洲高校首现KDD博士论文奖:清华裘捷中获Runner Up奖,WINNER奖也是位华人

【32. 图中的层次(图的广度优先遍历)】

维护数千规模MySQL实例,数据库灾备体系构建指南

Current relay JL-8GB/11/AC220V

Verilog语法基础HDL Bits训练 08

程序环境和预处理(详解)

单片机工程师笔试题目归纳汇总
随机推荐
如何用Golang来手撸一个Blog - Milu.blog 开发总结
IO/多路复用(select/poll/epoll)
13-GuliMall 基础篇总结
历时两月,终拿字节跳动offer,算法面试题分享「带答案」
京东二面痛遭中间件虐杀,30天学透这套中间件小册,挺进阿里
Another blast!Ali's popular MySQL advanced collection is open source, reaching P7
Matlab基础(1)——基础知识
牛客-TOP101-BM42
MySQL中的select,from, join, on where groupby等执行顺序
Summary of text alignment, line height, space, etc.
爱可可AI前沿推介(7.30)
明德扬FPGA开发板XILINX-K7核心板Kintex7 XC7K325 410T工业级
小心 transmittable-thread-local 的这个坑
LeetCode_235_Last Common Ancestor of Binary Search Tree
为什么说Prometheus是足以取代Zabbix的监控神器?
时间序列曲线相似性
流水线上的农民:我在工厂种蔬菜
2022-07-29 顾宇佳 学习笔记 异常处理
win下怎么搭建php环境的方法教程
SCM engineers written questions induction summary