当前位置:网站首页>最基础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;
}边栏推荐
猜你喜欢

Redis 主从复制

2022-07-29 Gu Yujia Study Notes Exception Handling

unity初学6——简易的UI制作(血条制作)和音频加入以及NPC的对话气泡(2d)

LeetCode_236_Last Common Ancestor of a Binary Tree

周鸿祎:微软抄袭了360安全模式 所以成为美国最大的安全公司

Current relay JL-8GB/11/AC220V

爱可可AI前沿推介(7.30)

横向对比5种常用的注册中心,无论是用于面试还是技术选型,都非常有帮助

概率论的学习和整理7:理解期望和方差还是要回到随机试验本身,期望不是平均值,方差的公式不同情况不同

SCM engineers written questions induction summary
随机推荐
LinkedList与链表
横向对比5种常用的注册中心,无论是用于面试还是技术选型,都非常有帮助
Get the original data API on 1688app
基于时延估计的扰动卡尔曼滤波器外力估计
概率论得学习整理--番外3:二项式定理和 二项式系数
Redis 主从复制
unity初学6——简易的UI制作(血条制作)和音频加入以及NPC的对话气泡(2d)
明德扬FPGA开发板XILINX-K7核心板Kintex7 XC7K325 410T工业级
AlphaFold预测了几乎所有已知蛋白质!涵盖100万物种2.14亿结构,数据集开放免费用...
概率论的学习整理--番外1:可重复且无次序的计数公式C(n+k-1,k) 的例题 : 同时丢3个骰子,会有多少种情况?答案不是216而是56!
Homework 7.29 correlation function directory and file attributes related functions
备战金九银十!2022面试必刷大厂架构面试真题汇总+阿里七面面经+架构师简历模板分享
基于声信道分析的电缆隧道人员定位技术
EXCEL解决问题:如何查找目标区域,是否包含指定字符串?
unity对象池(学习)
PanGu-Coder: 函数级的代码生成模型
Verilog grammar basics HDL Bits training 07
LeetCode_236_Last Common Ancestor of a Binary Tree
Underwater target detection method based on spatial feature selection
English line break