当前位置:网站首页>最基础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;
}
边栏推荐
猜你喜欢
打破原则引入SQL,MongoDB到底想要干啥???
C# 枚举类型 于xaml 中区别
超图iServer rest服务之最佳路径分析
京东二面痛遭中间件虐杀,30天学透这套中间件小册,挺进阿里
[BJDCTF2020]Cookie is so stable-1|SSTI injection
别被隐私计算表象骗了 | 量子位智库报告(附下载)
为什么说Prometheus是足以取代Zabbix的监控神器?
数据湖(十八):Flink与Iceberg整合SQL API操作
Verilog语法基础HDL Bits训练 07
Microsoft SQL server hacked, bandwidth stolen
随机推荐
Unity Beginner 6 - Simple UI production (blood bar production) and audio addition and NPC dialogue bubbles (2d)
External Force Estimation Based on Time Delay Estimation with Perturbed Kalman Filter
Homework 7.29 correlation function directory and file attributes related functions
概率论的学习和整理--番外4: 关于各种平均数:算术平均数,几何平均数,调和平均数,以及加权平均数和平方平均数 (未完成)
What happened when the computer crashed?
Verilog grammar basics HDL Bits training 07
Another blast!Ali's popular MySQL advanced collection is open source, reaching P7
Kubernetes 入门实战03 中级篇
JD.com was brutally killed by middleware on two sides. After 30 days of learning this middleware booklet, it advanced to Ali.
English line break
unity对象池(学习)
英 文 换 行
Matlab基础(2)——向量与多项式
模糊离散事件系统的可测性
[Cloud-Building Co-creation] Huawei Cloud and Hongmeng collaborate to cultivate innovative developers
概率论的学习整理1: 集合和事件
基于MySQL数据库,Redis缓存,MQ消息中间件,ES搜索引擎的高可用方案解析
IO/multiplexing (select/poll/epoll)
Js - 内置对象
概率论的学习整理--番外2:和二项式,组合相关的杨辉三角