Backpack problem is very classic, "backpack problem Nine" speak very detailed, suggest to take a look.
Here, I want to give 0-1 backpacks and complete backpack compression space after the implementation, that is, as long as a one-dimensional array.
The 0-1 backpack, unlike the complete backpack, is just the same as the order of the inner loop, so the code is basically the same.
I hope I can help you.
0-1 Backpack:
1#include <bits/stdc++.h>2 using namespacestd;3 intf[1001];4 intw[1001]; 5 intv[1001];6 intMain () {7 intN;8 intW;9Cin>>n>>W;Ten for(inti =1; i<=n;i++){ OneCin>>w[i]>>V[i]; A } -memset (f,-10000000,sizeof(f)); - for(inti =1; i<=n;i++){ the for(intj = w;j>=0; j--){ -F[J] = max (f[j],f[j-w[i]]+v[i]); - } - } + intMax =0; - for(inti =1; i<=n;i++){ + if(f[i]>max) { AMax =F[i]; at } - } -printf"%d", max); -}
Full backpack:
1#include <bits/stdc++.h>2 using namespacestd;3 intf[1001];4 intw[1001]; 5 intv[1001];6 intMain () {7 intN;8 intW;9Cin>>n>>W;Ten for(inti =1; i<=n;i++){ OneCin>>w[i]>>V[i]; A } -memset (f,-10000000,sizeof(f)); - for(inti =1; i<=n;i++){ the for(intj =0; j<=w;j++){ -F[J] = max (f[j],f[j-w[i]]+v[i]); - } - } + intMax =0; - for(inti =1; i<=n;i++){ + if(f[i]>max) { AMax =F[i]; at } - } -printf"%d", max); -}
"Backpack" 0-1 backpack with full backpack one-dimensional array implementation