Problem Description:
There are a total of N gems to choose from, the weight of gem I is WI, the attraction is Di, can only be used once. Bessie the maximum weight of a gemstone bracelet is M. Give the N,m,wi,di, beg M.
A very standard 01 knapsack problem. Code that uses an optimized one-dimensional array. Because for this kind of problem, only I-1 's f[v] is useful for calculating the f[v of I, so using a one-dimensional array is equivalent to overwriting the previous record before i-1.
Below is my code:
#include <iostream>#include<string.h>#include<stdio.h>#defineM 12880+10using namespacestd;intF[m];intw[3500],d[3500];intMain () {intn,m; scanf ("%d%d",&n,&m); Memset (F,0,sizeof(f)); for(intI=0; i<n;i++) {scanf ("%d%d", w+i,d+i); } for(intI=0; i<n;i++){ for(intj=m;j>=w[i];j--){ if(f[j]<f[j-w[i]]+D[i]) {F[j]=f[j-w[i]]+D[i]; }}} printf ("%d\n", F[m]); return 0;}
The time complexity of the algorithm is O (MN), and the space complexity is O (M);
poj3624 Simple 01 Knapsack problem