当前位置:网站首页>Dynamic planning: code summary of knapsack problem template
Dynamic planning: code summary of knapsack problem template
2022-07-28 20:40:00 【2,4(1H,3H)-PD are mine】
explain : according to acwing Algorithm improvement course and algorithm foundation course , The code is based on y In general, slightly modified .
1.0-1 knapsack problem
Problem model description :
Yes N Items and a capacity are V The backpack . Each item can only be used once .
The first i The volume of the item is vi, The value is wi. Find out which items to pack in your backpack , The total volume of these items can not exceed the capacity of the backpack , And the total value is the greatest .
The template questions :2. 01 knapsack problem - AcWing Question bank
Code ( Space optimized version ):
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int f[N];
int main()
{
int n,m;
cin>>n>>m; // Quantity and total volume
for(int i=0;i<n;++i){
int v,w; //v: Volume ;w: value
cin>>v>>w;
for(int j=m;j>=v;--j) f[j]=max(f[j],f[j-v]+w);
}
cout<<f[m];
return 0;
}2. Complete knapsack problem
Problem model description :0-1 Based on the knapsack problem , Every item can be selected indefinitely .
The template questions :3. Complete knapsack problem - AcWing Question bank
Code ( Optimize to O(n^2), One dimensional space ):
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int f[N];
int main()
{
int n,m;
cin>>n>>m; // Quantity and total volume
for(int i=0;i<n;++i){
int v,w; //v: Volume ;w: value
cin>>v>>w;
for(int j=v;j<=m;++j) f[j]=max(f[j],f[j-v]+w);
}
cout<<f[m];
return 0;
}3. Group knapsack problem
Problem model description :
Yes N Group items and a capacity are V The backpack . There are several items in each group , Only one item can be selected in the same group .
Find out which items to pack in your backpack , It can make the total volume of the goods not exceed the capacity of the backpack , And the total value is the greatest .
The template questions :9. Group knapsack problem - AcWing Question bank
Code :
#include<bits/stdc++.h>
using namespace std;
const int N=110;
int f[N],v[N][N],w[N][N],s[N];
int main()
{
int n,m;
cin>>n>>m; // Quantity and total volume
for(int i=1;i<=n;++i){
cin>>s[i]; // The first i Number of classes
for(int j=1;j<=s[i];++j) cin>>v[i][j]>>w[i][j];
}
for(int i=1;i<=n;++i)
for(int j=m;j>=0;--j)
for(int k=1;k<=s[i];++k)
if(v[i][k]<=j) f[j]=max(f[j],f[j-v[i][k]]+w[i][k]);
cout<<f[m];
return 0;
}4. The longest common ascending subsequence problem
This is not a backpack model , It's an interval dp, The complexity of simple practice is O(n^3), Put it here O(n^2) Complexity code .
Problem model description : Two sequences A and B, If they all contain a number whose position is not necessarily continuous , And the value is strictly increasing , Then we call this segment a common ascending subsequence of two sequences , And the longest of all the common ascending subsequences is the longest common ascending subsequence .
The template questions :272. The longest common ascending subsequence - AcWing Question bank
Code (O(n^2)):
#include<bits/stdc++.h>
using namespace std;
const int N=3010;
int n,a[N],b[N],f[N][N];
int main()
{
cin>>n;
for(int i=1;i<=n;++i) cin>>a[i];
for(int i=1;i<=n;++i) cin>>b[i];
for(int i=1;i<=n;++i){
int maxv=1;
for(int j=1;j<=n;++j){
f[i][j]=f[i-1][j];
if(a[i]==b[j]) f[i][j]=max(f[i][j],maxv);
if(b[j]<a[i]) maxv=max(maxv,f[i][j]+1);
}
}
int res=0;
for(int i=1;i<=n;++i) res=max(res,f[n][i]);
cout<<res;
return 0;
}5. The knapsack problem is the number of solutions
Problem model description :0-1 Based on the knapsack problem , Number of schemes of the most optimal method .
The template questions :11. The knapsack problem is the number of solutions - AcWing Question bank
Code :
#include<bits/stdc++.h>
using namespace std;
const int N=1010,mod=1e9+7;
int f[N],g[N];
int main()
{
int n,m;
cin>>n>>m;
g[0]=1;
for(int i=0;i<n;++i){
int v,w;
cin>>v>>w;
for(int j=m;j>=v;--j){
int mav=max(f[j],f[j-v]+w),cnt=0;
if(mav==f[j]) cnt+=g[j];
if(mav==f[j-v]+w) cnt+=g[j-v];
cnt%=mod;
g[j]=cnt;
f[j]=mav;
}
}
int res=0,ans=0;
for(int i=0;i<m;++i) res=max(res,f[i]);
for(int i=0;i<m;++i) if(res==f[i]) ans=(ans+g[i])%mod;
cout<<ans;
return 0;
}6. There is a knapsack problem of dependence .
Problem model description : Yes N One item and one capacity are V The backpack . There is a dependency between objects , And dependencies make up the shape of a tree . If you choose an item , You must select its parent node .
The template questions :10. There is a knapsack problem of dependence - AcWing Question bank
State means :f[u][m]: With u The subtree of the root node , At a cost of no more than m The maximum value generated by .
#include<bits/stdc++.h>
using namespace std;
const int N=110;
int h[N],ne[N],e[N],idx,v[N],w[N],f[N][N];
int n,m;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u)
{
for(int i=h[u];~i;i=ne[i]){
int son=e[i];
dfs(son);
for(int j=m-v[u];j>=0;--j)
for(int k=0;k<=j;++k)
f[u][j]=max(f[u][j],f[u][j-k]+f[son][k]);
}
for(int i=m;i>=v[u];--i) f[u][i]=f[u][i-v[u]]+w[u];
for(int i=0;i<v[u];++i) f[u][i]=0;
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof(h));
int r;
for(int i=1;i<=n;++i){
int p;
cin>>v[i]>>w[i]>>p;
if(p==-1) r=i;
else add(p,i);
}
dfs(r);
cout<<f[r][m];
return 0;
}7. Multiple knapsack problem
Problem model description :0-1 Based on the knapsack problem , The first i Choose at most items si Pieces of .
The template questions :5. Multiple knapsack problem II - AcWing Question bank
Code ( Binary optimized version ):
#include<bits/stdc++.h>
using namespace std;
const int M=2010,N=25000;
int v[N],w[N],f[M];
int main()
{
int n,m;
cin>>n>>m;
int cnt=0;
for(int i=1;i<=n;++i){
int a,b,s;
cin>>a>>b>>s;
int k=1;
while(k<=s){
++cnt;
v[cnt]=a*k,w[cnt]=b*k;
s-=k;
k<<=1;
}
if(s>0){
++cnt;
v[cnt]=a*s,w[cnt]=b*s;
}
}
n=cnt;
for(int i=1;i<=n;++i)
for(int j=m;j>=v[i];--j)
f[j]=max(f[j],f[j-v[i]]+w[i]);
cout<<f[m];
return 0;
}Sliding window optimization :
#include<bits/stdc++.h>
using namespace std;
const int N=20010;
int f[N],g[N],q[N];
int main()
{
int n,m;
cin>>n>>m;
for(int i=0;i<n;++i){
int v,w,s;
cin>>v>>w>>s;
memcpy(g,f,sizeof(f)); // Save one level of status
for(int j=0;j<v;++j){
int hh=0,tt=-1;
for(int k=j;k<=m;k+=v){
if(hh<=tt&&q[hh]<k-s*v) hh++;
if(hh<=tt) f[k]=max(f[k],g[q[hh]]+(k-q[hh])/v*w);
while(hh<=tt&&g[q[tt]]-(q[tt]-j)/v*w<=g[k]-(k-j)/v*w) tt--;
q[++tt]=k;
}
}
}
cout<<f[m];
return 0;
}
8. Combinatorial knapsack problem
Problem model description : Yes N Items and a capacity are V The backpack .
There are three kinds of goods :
- The first kind of goods can only be used 1 Time (01 knapsack );
- The second kind of goods can be used indefinitely ( Completely backpack );
- The third kind of goods can only be used at most si Time ( Multiple backpack );
The template questions :7. Mixed knapsack problem - AcWing Question bank
Code :
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int n,m;
int f[N];
int main()
{
cin>>n>>m;
for(int i=0;i<n;++i){
int v,w,s;
cin>>v>>w>>s;
if(s==0) // Completely backpack
for(int j=v;j<=m;++j) f[j]=max(f[j],f[j-v]+w);
else{
if(s==-1) s=1; //01 The number of backpacks is 1 Multiple backpacks
for(int k=1;k<=s;k*=2){
for(int j=m;j>=k*v;--j) f[j]=max(f[j],f[j-k*v]+k*w);
s-=k;
}
if(s) for(int j=m;j>=s*v;--j) f[j]=max(f[j],f[j-s*v]+s*w);
}
}
cout<<f[m];
return 0;
}
边栏推荐
- 关于正则的两道笔试面试题
- Windows系统下Mysql数据库定时备份
- Voice controlled robot based on ROS (II): implementation of upper computer
- 激光slam:LeGO-LOAM---代码编译安装与gazebo测试
- Teach you unity scene switching progress bar production hand in hand
- Pop up modal box
- Data mining (data preprocessing) -- Notes
- Explain rigid body and collider components in unity
- C language data 3 (2)
- Nocturnal simulator settings agent cannot be saved
猜你喜欢

Read JSON configuration file to realize data-driven testing

Raspberry pie 4B uses MNN to deploy yolov5 Lite

Nocturnal simulator settings agent cannot be saved

C language data 3 (2)

一个程序员的水平能差到什么程度?尼玛,都是人才呀...

Scheduled backup of MySQL database under Windows system

漂亮的蓝色背景表单输入框样式

Anaconda creation environment

Dsactf July re

Torch. NN. Linear() function
随机推荐
超大模型工程化实践打磨,百度智能云发布云原生AI 2.0方案
一文让你搞懂什么是TypeScript
C# 读取 CSV文件内数据,导入DataTable后显示
Tree row expression
Redis入门一:Redis实战读书笔记
PL515 SOT23-5 单/双口 USB 充电协议端口控制器 百盛电子代理商
LVM logical volume
Read JSON configuration file to realize data-driven testing
[dynamic link library (DLL) initialization example program failed "problem]
产品力大幅提升 新款福特探险者发布
Other IPS cannot connect to the local redis problem solving and redis installation
Pytorch model parameter assignment - tensor.copy_ () method
同质化代币与 NFT 结合,如何使治理结构设计更灵活?
[task02: SQL basic query and sorting]
Anaconda creation environment
UE4 3dui widget translucent rendering blur and ghosting problems
平均海拔4000米!我们在世界屋脊建了一朵云
Solve the problem that jupyter cannot import new packages
leetcode:2141. 同时运行 N 台电脑的最长时间【最值考虑二分】
js图表散点图例子