One-dimensional knapsack:
#include<iostream>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
int a[50001],b[50001];
for(int i=1;i<=n;i++)cin>>a[i]>>b[i];
int f[50001]={0};//重量为j的情况下最大价值
for(int i=1;i<=n;i++)
{
for(int j=m;j>=a[i];j--)
if(f[j-a[i]]+b[i]>f[j])
f[j]=f[j-a[i]]+b[i];
}
cout<<f[m]<<endl; //最优解
for(int i=1;i<=m;i++)
cout<<f[i];
return 0;
}
2D backpack
#include<iostream>
#include<math.h>
using namespace std;
int f[5001][5001]; // i row j column is the maximum value of the first i objects whose weight does not exceed j
int main()
{
int m,n;
cin>>n>>m;
int a[50001],b[50001];
for(int i=1;i<=n;i++)cin>>a[i]>>b[i] ;
for(int i=1;i<=n;i++)
for(int j=m;j>0;j--)
{
if(a[i]<=j)f[i][j]=max (f[i-1][j],f[i-1][ja[i]]+b[i]); //f[i-1][j] value when not taken, f[i -1][ja[i]]+b[i] The value after taking it //i is the first i object, j is the remaining backpack space else f[i][j]=f[i-1][j ]; } //cout<<f[n][m]<<endl; //Optimal solution for(int i=1;i<=n;i++) { for(int j=1;j<=m ;j++) cout<<f[i][j];cout<<endl;
}
return 0;
}