#include <stdio.h> int nn[10000],p[10000],f[10000][10000]; int max (int a,int b) { return a>b ? a:b; } int main () { int m,i,j,n,v; scanf ("%d",&m); while (m--) { scanf ("%d%d",&n,&v); for (i=1; i<=n; i++) { scanf ("%d",&nn[i]); } for (i=1; i<=n; i++) { scanf ("%d",&p[i]); } for (i=0; i<=n; i++) f[i][0]=0; for (i=0; i<=v; i++) f[0][i]=0; for (i=1; i<=n; i++) { for (j=0; j<=v; j++) { if (j>= p[i]) f[i][j] =max (f[i-1][j],f[i-1][j-p[i]]+nn[i]); else f[i][j]=f[i-1][j]; } } printf ("%d\n",f[n][v]); } return 0; }
一维数组的背包:
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> using namespace std; int t,n,v,W[1005],V[1005],dp[1005]; int main() { int i,j; scanf ("%d",&t); while (t--) { memset (dp,0,sizeof (dp)); scanf ("%d%d",&n,&v); for (i=1;i<=n;i++) scanf ("%d",&W[i]); for (i=1;i<=n;i++) scanf ("%d",&V[i]); for (i=1;i<=n;i++) { for (j=v;j>=V[i];j--) { if (dp[j] < dp[j-V[i]]+W[i]) dp[j]=dp[j-V[i]]+W[i]; } } printf ("%d\n",dp[v]); } return 0; }
一维数组的背包号称是 以空间换时间。上图第一个是一维,第二个是二维的。