Simple 0-1 Backpack Printing path problem, we can record a p[][] array to determine whether the current item is selected, and finally follow the record output, note is reverse.
#include <stdio.h> #include <string.h> int main () { int a[25],p[25][10005],i,j,n,m,s[ 10005]; while (scanf ("%d%d", &m,&n)!=eof) { for (i=1;i<=n;i++) scanf ("%d", &a[i]); Memset (s,0,sizeof (s)); memset (P,0,sizeof (P)); for (i=1;i<=n;i++) for (j=m;j>=a[i];j--) if (S[j-a[i]]+a[i]>s[j]) { s[j]=s[j-a[i]]+a[i]; P[i][j]=1; Use p[][] to record whether it is selected } j=m; for (i=n;i>=1;i--) if (P[i][j]) { printf ("%d", a[i]);//positive sequence output to open an array record again, this is anti- j-=a[i]; } printf ("sum:%d\n", S[m]); } return 0; }
The next recursive version, the basic idea is the same, we still look at the code.
Recursive version #include<iostream> #include <stdio.h> #include <string.h>using namespace std; #define MAX (x, y) >y? x:y) int dp[13000],a[1000][1000],w[13000],f[10000],count=0;void print (int n,int m) {if (n==0) return; if (a[n][m]==0) print (n-1,m); else {print (n-1,m-w[n]); F[count++]=w[n]; }}int Main () {int n,m; while (scanf ("%d%d", &m,&n) >0) {int i; for (i=1;i<=n;i++) scanf ("%d", &w[i]); Memset (Dp,0,sizeof (DP)); memset (A,0,sizeof (a)); a[0][0]=1;//Otherwise the function does not terminate for (i=1;i<=n;i++) {for (int j=m;j>=w[i];j--) { Dp[j]=max (Dp[j],dp[j-w[i]]+w[i]); if (Dp[j]==dp[j-w[i]]+w[i]) a[i][j]=1; }} count=0; Print (N,M); for (i=0;i<count;i++) {printf ("%d", f[i]); } printf ("sum:%d\n", Dp[m]); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0-1 Backpack print path (recursive and non-recursive versions)