Table of contents
2.1 Two-dimensional dynamic programming
2.1.1 How to transfer: f[i][j]
2.1.2 Initialization: f[0][0]=0
2.1.3 Time complexity: O(n^2) million level
2.1.4 Space complexity: two-dimensional million level 4*1000000/1024/1024≈4MB
foreword
After learning the general algorithm of y, I wrote a little thought
1. Problem
There are N items and a backpack with capacity V. Each item can only be used once.
The i-th item has volume vi and value wi.
Solve which items to put into the backpack so that the total volume of these items does not exceed the capacity of the backpack and the total value is the largest.
output the maximum value.
2. Thinking
2.1 Two-dimensional dynamic programming
f[i][j] means only looking at the first i items, when the total volume is j, what is the maximum total value
result=max{f[n][0~v]}
2.1.1 How to transfer: f[i][j]
(1) Do not select the i-th item: f[i][j]=f[i-1][j]
(2) Select the i-th item: f[i][j]=f[i-1][jv[i]]
2.1.2 Initialization: f[0][0]=0
2.1.3 Time complexity: O(n^2) million level
2.1.4 Space complexity: two-dimensional million level 4*1000000/1024/1024≈4MB
3. Code implementation
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1005;
int v[N],w[N];
int f[N][N];
int n,m;
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d%d",&w[i],&v[i]);
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(j<w[i])
f[i][j]=f[i-1][j];
else
f[i][j]=max(f[i-1][j],f[i-1][j-w[i]]+v[i]);
}
}
printf("%d\n",f[n][m]);
return 0;
}
4. Test sample
4.1 Input sample
4 5
1 2
2 4
3 4
4 5
4.2 Output results
8
4.3 Actual Results
Figure 1